简体   繁体   English

我如何编写此PHP代码来更好地调用WordPress中的类别帖子?

[英]How would I write this PHP code for calling category posts in WordPress better?

I am new to PHP and I tried my hand at coding a call for recent posts in a category, however it seems that I got into an echo loop. 我是PHP的新手,我曾尝试编写一个类别中最近帖子的调用代码,但是似乎我陷入了回声循环。

How would I optimize the following code so that it did not look, well, like it does? 我将如何优化以下代码,使其看起来不像它看上去的那样好?

<?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; ?>

Thanks so much, I look forward to learning programming and want to make my code at least conform to so kind of norm. 非常感谢,我期待学习编程,并希望使我的代码至少符合这种规范。

You just have to format and indent that code properly and use PHP templating instead of echo : 您只需要正确格式化和缩进该代码,然后使用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; ?>

If you don't want to alternate between PHP and HTML, you can just stick to PHP. 如果您不想在PHP和HTML之间切换,则可以坚持使用PHP。 This is just another way to write the same thing. 这只是写同一件事的另一种方式。

<?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>';
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM