0

I want to query a custom post type cpt_locations if the office_locations layout is selected in a flexible content field. I'm sure I have the standard syntax, but if I view the page it prints yes many times then hangs - as if it's looping infinitely. In my content-page.php I have:

if( get_row_layout() == 'office_locations' ):

    $args = array(
     'post_type'=> 'cpt_locations',
     'posts_per_page' => 10
    );              

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

                echo 'yes'; 

        }
        wp_reset_postdata();
    }
    wp_reset_query();

endif;

In page.php I'm already in a loop - is this the problem?:

<?php
    while ( have_posts() ) :
        the_post();

        get_template_part( 'template-parts/content', 'page' );

        if ( comments_open() || get_comments_number() ) :
            comments_template();
        endif;

    endwhile;
?>
1

You are missing $locations->the_post() in your loop:

if ( $locations -> have_posts() ) {
    while ( $locations -> have_posts() ) {
        $locations->the_post(); // Needed

        echo 'yes'; 
    }
}

One of the things this function does is advance $locations to the next post. Without it $locations->have_posts() will just repeat infinitely for the first post.

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.