Support

Account

Home Forums Front-end Issues Query Custom Posts in Page template breaks Custom Fields

Solved

Query Custom Posts in Page template breaks Custom Fields

  • Hi,

    I have a template page where ACF is applied to.

    On that page I would like to visualise all Custom Posts of a certain Custom Posts Type “Vacancies”. This is how i accomplish that:

    
    <?php
      $args = array( 'post_type' => 'Vacancies');
      $loop = new WP_Query( $args );
      while ( $loop->have_posts() ) : $loop->the_post();
        get_template_part( 'template-parts/vacancies', get_post_format() );
      endwhile;
    ?>
    

    Now underneath this code I would like to visualise some extra text so I’ve made some extra Custom Fields. Then I insert this code underneath above Custom Post Type code block:

    
    <?php if(the_field('vacancy-section-2-title')){
      echo the_field('vacancy-section-2-title');
    } ?>
    

    But the extra text is not showing on my page. I’m sure it has something to do with the Custom Post Type code block because when I remove it or I move the extra Custom Fields to the top it works.

    Why is this happening? Does new WP_Query change something so Custom Fields isn’t working anymore underneath it?

  • I was 5 minutes to early to post the question above as I’ve found the solutions after looking into WordPress Manual.

    Seems that if you call another post_type (in my case vacancies) with new WP_Query, WordPress is opening that (lexical) post_type environment. This means that most functions like ACF’s the_field() will try to look inside the custom post type “Vacancies” if the custom field “vacancy-section-2-title” exists. Obvious it’s not so i need to “Reset the Query” back to the original one.

    The solution is putting this function wp_reset_query() at the end of the custom posts loop.

    
    <?php
      $args = array( 'post_type' => 'Vacancies');
      $loop = new WP_Query( $args );
      while ( $loop->have_posts() ) : $loop->the_post();
        get_template_part( 'template-parts/vacancies', get_post_format() );
      endwhile;
      wp_reset_query()
    ?>
    

    Hope it helps other people in the future!

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

The topic ‘Query Custom Posts in Page template breaks Custom Fields’ is closed to new replies.