0

I'm using a code to show related posts on the page on one of the posts. It works OK, but I've just noticed that it makes the next part of the code to stop working as expected.


$custom_terms = wp_get_post_terms( get_the_ID(), 'categoria');
$args = array(
  'post_type' => 'oferta',
  'posts_per_page' => 6,
  'no_found_rows' => true,
  'tax_query' => array(             
       array(
          'taxonomy' => 'categoria',
          'field' => 'slug',
          'terms' => $custom_terms[0]->slug, 
      ),
   )
);

// Assign the current post ID to a variable.
$current_post_id = get_the_ID();

// Make the custom posts query.
$loop = new WP_Query( $args );

// Post counter; if the value has reached 5, then we exit the `while` loop below.
$counter = 0;

// Display the posts.
echo '<ul>';
while ( $loop->have_posts() ) {
    if ( $counter >= 5 ) {
        break;
    }

    $loop->the_post();
    // Display the post if it's not the current post with the ID $current_post_id
    if ( $current_post_id !== get_the_ID() ) {
        echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
        $counter++;
    }
}
echo '</ul>';

That works as expected. It shows up to 5 related posts, not including the current post (the post you are visiting).

But then I have other code that is supposed to get the title of the current post.

echo '<h2>Más datos de ' . get_the_title($post->ID) . '</h2>';

This line works OK if I put it before the code for related posts (it shows the title of the current post). But if I put this line after the code for related posts, then it shows the title of one of the related posts instead of the title of the current post.

I guess the code for related posts is messing with the $post->ID part, but I don't know enough PHP to know how to solve this.

Any tips or ideas would be much appreciated. Thanks!

1 Answer 1

1

It seemed like you did not call wp_reset_postdata() which in short, restores the context of the template tags (e.g. the_title() and get_the_title()) from a secondary query loop back to the main query loop.

More details at https://developer.wordpress.org/reference/functions/wp_reset_postdata/#more-information.

So basically, you just need to call wp_reset_postdata() like so, and then the issue in question would disappear:

echo '</ul>';

// Restores the $post global.
wp_reset_postdata();

// Now this should show the correct title.
echo '<h2>Más datos de ' . get_the_title($post->ID) . '</h2>';
1
  • 1
    That's it, solved. Thanks!
    – migueltic
    Commented Oct 27, 2022 at 5:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.