0

I'm making a box in my sidebar that shows a list of articles from a single category:

 <?php
// The Query
query_posts('cat=31&posts_per_page=5');
// The Loop
while ( have_posts() ) : the_post();
?>

<li><a href="<?php the_permalink(); ?>"><i class="fa fa-book"></i> <?php the_title(); ?></a> <span>Di <?php the_author(); ?>, <?php the_time('d/m/Y'); ?></span></li>

<?php
endwhile;
// Reset Query
wp_reset_query();
?>

But, this piece of code doesn't work. The <ul> tag is empty when the page is rendered.

1
0

This should work (if your post_type is not post you will need to amend the code)

<?php
$args = array(
'post_type' => 'post',
'cat'  => '31',
'posts_per_page' => 5,
);

$query = new WP_Query( $args );?>

    <?php if( $query->have_posts() ) : ?>

    <?php while( $query->have_posts() ) : $query->the_post(); ?>    

    <li><a href="<?php the_permalink(); ?>"><i class="fa fa-book"></i> <?php the_title(); ?></a> <span>Di <?php the_author(); ?>, <?php the_time('d/m/Y'); ?></span></li>

<?php

endwhile;
endif;
// Reset Query
wp_reset_query();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.