1

I used WP_Query to find posts of a certain criteria and loop through them performing actions. I grabbed the post id in the loop and assigned it to a variable $i to perform functions on.

Before the loop I used get_the_id() and it correctly displays the custom post page ID I am on. After the loop I used it again but this time it finds the id of the post I searched for.

Why does this happen?

function display_meta_box( $category ) 
{
    if (in_array('case_studies', get_post_types()))
    {

//get_the_id() - works fine here

        $combo_case_studies = esc_html( get_post_meta( $category->ID, 'cat', true ) ); 

        $args = array( 'post_type' => 'case_studies');  
        $loop = new WP_Query( $args );
        $i = '';

        while ( $loop->have_posts() ) : $loop->the_post();

            if ($combo_case_studies == get_the_title()) 
            {
                $i = get_the_id(); // correct?
            }

        endwhile;

...do stuff using $i...

//get_the_id() - gets a different ID

    }
}

I'm thinking of scrapping $i in its current implementation and instead doing this, but it still raises the question am I performing this loop correctly? And why is the page ID still different even after the loop?

function display_meta_box( $category ) 
{
        if (in_array('case_studies', get_post_types()))
        {

        $orig_i = get_the_id()


        ...loop stuff...


        ...use $orig_i keeping the ID from the get_the_id() before the loop...

        }
}
4

If you need to get the ID from the current page, you should make use of get_queried_object_id() which will return the ID of the current queried object.

A new instance of WP_Query alters the $post global variable, that is why after your loop you'll see the value of the last post from your custom query if you a var_dump($post);

This is why it is so important to reset all new instances of WP_Query as it does change the variables. To do this, just add wp_reset_postdata(); after your custom loop

Remember, if you need a counter, there is a build in loop counter, $current_post which you can access in your case via $loop->current_post. Just remember, this counter starts at 0

0

Try <?php wp_reset_query(); ?> after the while loop, this will reset your custom query data, so that you can retrieve the actual post/page data.

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.