1

I am trying to show 5 posts from a category in my home footer. I have placed this code

<?php query_posts( 'category_name=entertainment&posts_per_page=5' ); ?>

right in my home.php file and everything works fine except more than 5 posts are showing. In fact it is showing all the posts from that category. I have also tried showposts=5 but still it is not working.

this is the full code in my home.php

    <?php query_posts( 'category_name=entertainment&posts_per_page=5' ); ?>
 <?php
if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { die(); }
if (CFCT_DEBUG) { cfct_banner(__FILE__); }

if (have_posts()) {
    echo '<ul class="disclosure table group">';
    while (have_posts()) {
        the_post();
?>
    <li>
<?php

        if(has_post_thumbnail())
{ the_post_thumbnail();}    cfct_excerpt();

?>
    </li>
<?php
    }
    echo '<li class="pagination">', cfct_misc('nav-list'),'</li>';
    echo '</ul>';
}

?>    
1

First: don't use query_posts. Second: use $wp_query instead:

$args = array (
  'category_name' => 'entertainment',
  'posts_per_page'=> 5
  );
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
    }
else {
    // no posts found
    }
  • please add the full code with the $wp_query. And because i want to get the design of my post page. i copied the whole of my loop under this code <?php query_posts( 'category_name=entertainment&posts_per_page=5' ); ?> – Tarrmie de Man Mar 30 '17 at 20:32
  • That is the full code. You'll have to adapt the loop yourself according to your design. – cjbj Mar 31 '17 at 7:14
0

I would suggest you to use get_posts() function. With below code you'll get 5 post object-

$args = array (
  'category_name' => 'entertainment',
  'posts_per_page'=> 5
);

$posts = get_posts($args);

Here at $posts variable you'll get the 5 posts.

  • could you please add the full code with the get function – Tarrmie de Man Mar 30 '17 at 20:29
  • That is the full code. In $posts you'll get an array of post objects. then run a foreach loop to show the post as you want. Better do a print_r on $posts and examine the structure. Then replace it with foreach loop. – CodeMascot Mar 30 '17 at 20:32
  • did not work. maybe am not doing something right. i copied the post and pasted in my footer/home.php file. seriously am sorry but am a newbie in this. where exactly and how should i place the code in my file – Tarrmie de Man Mar 30 '17 at 20:49

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.