srccon
srccon

Reputation: 5

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.

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.

Upvotes: 0

Views: 404

Answers (2)

425nesp
425nesp

Reputation: 7593

If you don't want to alternate between PHP and HTML, you can just stick to 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>';
}

?>

Upvotes: 1

elclanrs
elclanrs

Reputation: 94141

You just have to format and indent that code properly and use PHP templating instead of 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; ?>

Upvotes: 2

Related Questions