如何编写PHP代码,更好地调用WordPress中的分类帖子?

如何编写PHP代码,更好地调用WordPress中的分类帖子?,php,wordpress,Php,Wordpress,我是PHP新手,我尝试过为最近的文章编写一个类别调用代码,但似乎我进入了一个echo循环 我该如何优化下面的代码,使它看起来不像它那样 <?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

我是PHP新手,我尝试过为最近的文章编写一个类别调用代码,但似乎我进入了一个echo循环

我该如何优化下面的代码,使它看起来不像它那样

<?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模板,而不是
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; ?>

您只需正确格式化和缩进代码,并使用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; ?>

如果你不想在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>';
}

?>

如果你不想在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>';
}

?>


谢谢,这真的很有帮助,我想我没有想到我可以在PHP中加入html。谢谢,这真的很有帮助,我想我没有想到我可以在PHP中加入html。