I have a single-page.php with a standard while loop. Inside that loop I have another loop that I want to output the post title that I am on/viewing, however because I have the get_the_title() within the inner loop of function futureEvent, its outputting that post's title instead:
while (have_posts()) {
the_post(); ?>
...
$futureEvents = get_posts($args);
foreach ($futureEvents as $post) {
$futureEvents = new WP_Query($args);
if ($futureEvents->have_posts()) {
echo '<div class="related-content"><h3>Upcoming ' . get_the_title() . ' Events</h3></div>';
?>
<article class="post-item">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</article>
}
}
}
In wordpress, I have a CPT with three posts added.
I have used get_the_title(118), however that hard-codes a post's id, but I want to get the title for any post from my CPT.
I have tried using get_the_title($post->$ID) and get_the_title($post_id), but that still outputs the incorrect post title.
Can anyone see how I can get the post title for the one I am on/viewing from inside that loop?
how I can get the post title for the one I am on/viewing from inside that loop?
You can use:
get_queried_object()
to get the full post object (a WP_Post
instance) of the current post you're on/viewing.
get_queried_object_id()
to get just the ID of the post you're on/viewing.
So for example in your inner loop, you could display the above post's title like so:
echo '<div class="related-content"><h3>Upcoming ' . get_the_title( get_queried_object() ) . ' Events</h3></div>';