quokka-web
quokka-web

Reputation: 104

Wordpress, global post changed after query

I am developing a plugin. In this plugin, I've created a custom post type 'toto'.

In the admin page, I edit a custom post element with the following post id '82'. In this page, I launch a query to retrieve elements with another post_type like that :

$featured_args = array(
'post_type' => 'other_type',
'post_status' => 'publish'    
);

// The Featured Posts query.
$featured = new WP_Query( $featured_args );

// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
    while ( $featured->have_posts() ) {
        $featured->the_post();
        if ( has_post_thumbnail( $featured->post->ID ) ) {
            /// do stuff here
        }
    }

// Reset the post data
wp_reset_postdata();
}

Doing that the global $post changed. It is not the post with the id 82 anymore but the latest post element from the query.

I thought that the wp_reset_postdata() function will allow me to retrieve my current $post. I also tried with wp_reset_query() without changes. Am I missing something?

Any help would be appreciated.

Upvotes: 1

Views: 1042

Answers (1)

Max
Max

Reputation: 765

wp_reset_postdata() resets the main loop. If you want to access $post directly try

global $post;
$backup_post = $post;

//do another loop

wp_reset_postdata();

$post = $backup_post;

Upvotes: 5

Related Questions