0

i am in a situation, i am creating a custom wordpress theme but i am stuck over something.

in my index/home page, firstly i am displaying 6 posts by category like below

<?php $posts = get_posts('category=2&numberposts=6'); foreach($posts as $post) {
      <h2><?php the_title(); ?></h2>
<?php } ?>

Now After displaying 6 post successfully by category, i want to display the most recent posts using the main post loop using code below.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
     <h2><?php the_title() ?></h2>
     _e('<p class="nopost">Sorry, no posts matched your criteria.</p>');
endif;?>

The Problem:

My home page is showing 6 post by category very well with no errors but in recent posts section of my home page, instead of showing recent posts the section is showing up the same post as there were in above category post.

i guess there must be a way to reset the query after displaying the category post. Please help me out.

  • Also when i am removing the get post by category code, the recent posts are appearing as i wanted – EpicNeer Jun 7 '15 at 8:57
  • 1
    Do not use $posts, rather use another variable like $posts_query, and add wp_reset_postdata(); after your foreach loop. – Pieter Goosen Jun 7 '15 at 9:00
  • Also, after this line, foreach($posts as $post) {, add setup_postdata( $post ) in order to make the use of template tags available – Pieter Goosen Jun 7 '15 at 9:02
  • you made my day, thanks for saving my time. @pieter goosen – EpicNeer Jun 7 '15 at 9:04
  • @pietergoosen : why did you post a comment instead of a proper answer? – s_ha_dum Jun 7 '15 at 12:43
3

Your problem is your custom query. Do not use variables that is used by default by Wordpress. $posts and $post is Wordpress reserved global variables. Change $post to a unique variable, something like $posts_query.

When using get_posts and you need to setup postdata to make use of template tags, you have no choiche but to use $post as setup_postdata() needs $post to be passed to it. This breaks the main query $post global, so you need to reset that once done. This is done with wp_reset_postdata().

Just a note on your code, template tags are not available by default when usng get_posts, so you need to add setup_postdata( $post ); inside your foreach loop to make the use of template tags available

Your custom query should look something like this

$posts_query = get_posts( 'YOUR ARGUMENTS' );
if ( $posts_query ) {
    foreach ( $posts_query as $post ) {
        setup_postdata( $post ); 

        // You can now use template tags like the_title() and the_content()

    }
    wp_reset_postdata();
}

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.