Support

Account

Home Forums Front-end Issues get_template_part( ) and the_field() don’t get along.

Solving

get_template_part( ) and the_field() don’t get along.

  • I created this custom type, and the WP_Query() is in a partial. So, I have a custom field, and right before the_field() I have a get_template_part(). The HTML and the CSS work fine but when I replace the HTML with the get_template_part() the the_field() after it shows nothing. When I view the source I don’t see the content generated by the_field(), it is empty. The get_template_part() pulls the content just fine but the the_field() after it is blank, with no data. Have you seen something like this before?

  • The only reason that this should happen is if the code in the template part is somehow modifying the current post and not resetting it properly.

  • This is the template part:

    <?php
    $sponsorsList = new WP_Query([
    	'posts_per_page' => -1,
    	'order' => 'ASC',
    	'post_type' => 'sponsor'
    ]);
    
    while($sponsorsList->have_posts()) {
    	$sponsorsList->the_post(); ?>
            <span class="md:block xs:hidden">
                <?php the_content(); ?>
            </span>
    
    <?php } ?>

    The classes are to show on large devices and hide on small devices. I thought at first that maybe a CSS class was causing the problem but this is not the case.

    Again, only the_fields() placed after the get_template_part() section are affected by it. I have no idea where to go from here.

  • Yes, you are doing a query, this will cause the global $post value to be updated. This must be reset after your loop with

    
    wp_reset_post_data();
    
  • Fixed! I totally forgot about it. Thanks.

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

You must be logged in to reply to this topic.