It could be that global $post is unreliable. Maybe turn on error logs via wp-config.php and log the post object in your function when it’s wrong:
global $post;
error_log( print_r( $post, 1 ) );
It could be that one of your templates is calling WP_Query without resetting the global $post. You could also try resetting the query at the top of your function before calling the global $post object:
wp_reset_postdata() should work but you could also call wp_reset_query() and see if one of those solves the issue.
Thread Starter
ADvi
(@advi)
The result of error_log( print_r( $post, 1 ) );
https://pastebin.com/ESjCmeGF
function ub_related_post_by_shop() {
wp_reset_query();
//wp_reset_postdata();
global $post;
error_log( print_r( $post, 1 ) );
$post_terms = wp_get_object_terms($post->ID, 'shop', array('fields'=>'ids'));
.....
wp_reset_query(); and wp_reset_postdata(); don’t solve the problem.
Here is my template https://pastebin.com/te6mW98z that is called from index.php (https://pastebin.com/Xbc0QZvU)
And this is content-header.php that is called from template https://pastebin.com/L5KixpWV
Can you please take a look?
Thanks.
-
This reply was modified 7 years, 7 months ago by
ADvi.
Well, the issue is that in your WP_Query() you’re querying post_type => 'post' but in the error logged post the post type there is promotion. If you’re trying to just get posts, the global $post isn’t always going to be a post type of post, sometimes it will be a page or whatever the post type of the current page is.
Check where promotion is being queried, if through a custom query make sure the wp_reset_postdata() is being called. If it’s a promotion page where the queried object is expected to be a promotion then you’ll need to rethink your function.