I have a custom post type (activities) and on each post I loop through another custom post type (tours).
In this second loop I want to create a variable containing the current post's name so I can use it to check if the tour contains the current page's activity.
I tried creating the variable before starting the second loop but it's lost and outputs nothing if I try to echo this in the second loop. This is probably obvious to most PHP and Wordpress developers so I'm sorry for my lack of knowledge here!
Here a simplified version of my code
<?php // start the activities loop ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php // Get current post name ?>
<?php $current_page = $post->post_name; ?>
<?php $args = array(
'post_type' => 'tours'
);
$tours_query = new WP_Query($args);
?>
<?php if($tours_query->have_posts()): ?>
<?php while($tours_query->have_posts()): $tours_query->the_post(); ?>
<?php the_title(); ?>
<?php while(have_rows('itinerary')):the_row('itinerary'); ?>
<?php $posts = get_sub_field('activity'); ?>
<?php if($posts): ?>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>
<?php // the permalink and title shown below are correct ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php // Trying to get the current post name to use here ?>
<p>current post = <?php $current_page; ?></p>
<?php endforeach; ?>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php else: ?>
<p>No activities found</p>
<?php endif; ?>
<?php endwhile; ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Thanks in advance for any help :)