• Hi. Can you help me please and tell what i’m doing wrong?

    There is a function ub_releted_post_by_shop() (https://pastebin.com/7WcBCcyq) that returns a list of posts from blog, this posts have the same taxonomy as the current post type

    If I call this function inside single post then everything is fine, I ‘ve got needed posts.

    But when I’m on the homepage or in archive then this function returns wrong posts (not by taxonomy terms)

    Frontpage is formed by index.php that has some templates for different post types (https://pastebin.com/Xbc0QZvU).

    Why function (code) returns wrong posts on homepage?

    Thanks for advices.

Viewing 3 replies - 1 through 3 (of 3 total)
  • 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 6 years, 5 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.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Function gets wrong ID of posts’ is closed to new replies.