0

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 :)

1
  • Can you please show me how's your activities custom post type query ? Commented Oct 3, 2018 at 6:08

1 Answer 1

1

What you've done with the variable is correct (defining it before starting the next loop), but you're not outputting it correctly:

<p>current post = <?php $current_page; ?></p>

If you want to output $current_page to the screen, you need to echo it:

<p>current post = <?php echo $current_page; ?></p>
1
  • Thank you Jacob, I spotted my error yesterday while going through my code again, such a stupid one. Thank you for being so polite in your answer! Commented Oct 5, 2018 at 20:09

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.