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!