0

I am a creating a shortcode to return posts from a custom post type, along with specific ACF fields. Everything is working fine except for the first post not returning it's post meta info.

My code:

$args = array(
    'post_type' => 'show',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'orderby'   => 'meta_value',
    'meta_key'  => 'show_date',
    'order' => ASC
);

$output = '';

$query = new WP_Query( $args );
if( $query->have_posts() ){

    $output .= '<h1>The Showlist</h1>';

    while( $query->have_posts() ){

        $show_date = get_field('show_date');
        $show_venue = get_field('show_venue');

        // print '<pre>';
        // print_r($show_date);
        // print '</pre>';

        $query->the_post();
        $output .= '<h3>' . get_the_title() . ' @ <a href="/venue/' . $show_venue->post_name . '">' . $show_venue->post_title . '</a></h3>';
        $output .= '<p>' . $show_date . '</p>';
    }

}
wp_reset_postdata();

// do shortcode actions here
return $output;

An example of what I am getting:

  • Showlist Title -
  • Showlist Title - Show Venue - Show Date
  • Showlist Title - Show Venue - Show Date
  • Showlist Title - Show Venue - Show Date
  • Showlist Title - Show Venue - Show Date
  • Showlist Title - Show Venue - Show Date
  • Showlist Title - Show Venue - Show Date

I am not sure why the first item is not returning the meta info. I have double check that it does contain the information in the backend.

Any ideas? TIA.

3
    $show_date = get_field('show_date');
    $show_venue = get_field('show_venue');

    // print '<pre>';
    // print_r($show_date);
    // print '</pre>';

    $query->the_post();

You are setting the active post AFTER getting the values.

Put $query->the_post() always at the top of that while loop, so that the other functions can rely on the global $post variable being set correctly.

  • Thank you so much, I knew it had to be something simple that I overlooked. – Matthew Woodard Jan 29 '18 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.