【问题标题】:How would I write this PHP code for calling category posts in WordPress better?我将如何编写这个 PHP 代码来更好地调用 WordPress 中的类别帖子?
【发布时间】:2013-04-06 10:27:21
【问题描述】:

我是 PHP 新手,我尝试编写调用某个类别中最近帖子的调用,但似乎我进入了回显循环。

我将如何优化以下代码,使其看起来不像它的样子?

<?php $cat_id = 3;
$latest_cat_post = new WP_Query( array('posts_per_page' => 1, 'category__in' => array($cat_id)));
if( $latest_cat_post->have_posts() ) : while( $latest_cat_post->have_posts() ) : $latest_cat_post->the_post();
echo '<a href="';
the_permalink();
echo '">';
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
echo '</a>';
echo '<div class="widget-box-text">'
echo '<a href="';
the_permalink();
echo '">';
the_title();
echo '</a>';
the_excerpt();
echo '</div><!-- widget-box-text -->'
endwhile; endif; ?>

非常感谢,我期待学习编程,并希望我的代码至少符合这种规范。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您只需正确格式化和缩进该代码并使用 PHP 模板而不是 echo:

    <?php
    $cat_id = 3;
    $query = new WP_Query(array(
      'posts_per_page' => 1,
      'category__in' => $cat_id
    ));
    ?>
    
    <?php while ($query->have_posts()): $query->the_post(); ?>
      <a href="<?php the_permalink(); ?>"></a>
      <?php if (has_post_thumbnail()) the_post_thumbnail(); ?>
      <div class="widget-box-text">
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php the_excerpt(); ?>
      </div>
    <?php endwhile; ?>
    

    【讨论】:

    • 谢谢,这真的很有帮助,我想我没有想到我可以在 html 中穿插 PHP。
    【解决方案2】:

    如果您不想在 PHP 和 HTML 之间交替使用,您可以坚持使用 PHP。这只是编写相同内容的另一种方式。

    <?php
    
    $cat_id = 3;
    $query = new WP_Query
    (
        array
        (
            'posts_per_page' => 1,
            'category__in' => $cat_id
        )
    );
    
    while($query->have_posts())
    {
        $query->the_post();
    
        echo  '<a href="'.the_permalink().'"></a>';
    
        if (has_post_thumbnail()){
            the_post_thumbnail();
        }
    
        echo  '<div class="widget-box-text">'
                    .'<a href="'.the_permalink().'">'.the_title().'</a>';
    
        the_excerpt();
    
        echo '</div>';
    }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2011-12-03
      相关资源
      最近更新 更多