Support

Account

Home Forums General Issues Issue with setup_postdata

Solving

Issue with setup_postdata

  • On my single post template, I hook a partial template using the following code in order to display related products above the post content :

        <?php if ( have_rows( 'featured_products' ) ) : ?>
        <?php while ( have_rows( 'featured_products' ) ) :
        the_row(); ?>
    
        <?php if ( $headline = get_sub_field( 'headline' ) ) : ?>
        <?php echo esc_html( $headline ); ?>
        <?php endif; ?>
    
        <?php
        $product = get_sub_field( 'product' );
        if ( $product ) :
            $post = $product;
            setup_postdata( $post ); 
            print_r($post);
            ?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php wp_reset_postdata(); ?>
        <?php endif; ?>
    
        <?php endwhile; ?>
        <?php endif; ?>

    The headline value is returned correctly. However, when it comes to product, it returns values of the current post (and not the related post). As you can see setup_postdata is here, so I don’t really understand… In addition print_rreturns the correct values.

    Any idea ?

  • How is your partial template loaded? Are you using get_template_part() or are you doing it another way?

  • This reply has been marked as private.
  • The reason that it’s not working is that you’re not using get_template_part(). When you use get_template_part() WP declares the global $post variable for use in your template, along with many other global variables that are used in templates.

    You either need to switch to get_template_part() or you need to declare the global variables yourself at the top of your file global $post;

  • This reply has been marked as private.
  • This reply has been marked as private.
  • This reply has been marked as private.
  • It could have been one of the numerous other globals that are available when using get_template_part()

Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.