Forums

[resolved] Multiple loops and current $post->ID (3 posts)

  1. cooperanet
    Member
    Posted 2 years ago #

    Hi,

    In one of my theme I use multiple loops using new WP_Query.

    Example: my content contains a classic loop calling a page or a post and my sidebar contains two custom loops calling one specific page or post.

    /* sidebar loops */
    <?php $customLoop1 = new WP_Query('page_id=5');?>
    <?php while ($customLoop1->have_posts()) : $customLoop1->the_post() ;?>
    <!-- content stuff here -->
    <?php endwhile; ?>
    
    <?php $customLoop2 = new WP_Query('page_id=10');?>
    <?php while ($customLoop2->have_posts()) : $customLoop2->the_post() ;?>
    <!-- content stuff here -->
    <?php endwhile; ?>

    The problem now: if I put this code below these loops:

    <?php echo $post->ID; ?>

    It returns me the ID of each post/page calling by the custom loop and not the ID of the current post. And I think it's normal.

    But, how to retrieve the current post ID outside of the classic loop?

    Any help would be greatly appreciated!

  2. MichaelH
    Volunteer
    Posted 2 years ago #

    In that first loop the Post ID would be

    <?php echo $customLoop1->post->ID; ?>

    But $posts[0]->ID would be the id of the first post in the $posts array

    Note you might want to put a wp_reset_query(); after your endwhile when using a custom loop to properly reset the normal query values.

  3. cooperanet
    Member
    Posted 2 years ago #

    Great! I didn't know the wp_reset_query() function. A nice way to reset!
    Thanks a lot for your help!

Topic Closed

This topic has been closed to new replies.

About this Topic