0

I have a short query that is supposed to load IDs from pages that the user picks in the backend. Currently it does display an array with IDs on the frontpage, but it stops displaying posts after the first one.

Code that I use to get the IDs from the field:

  <?php 
    $value = get_field('event_hotels', false);
    var_dump($value);

    $print = implode(',', $value);
    echo $print;
  ?>

This outputs '158,67,136,153' in my example.

Next, I load this into a WP Query:

    $args = array('post_type' => 'hotel', 'p' => $print, 'posts_per_page' => 20, 'orderby' => 'title', 'order' => 'ASC');
    var_dump($args);
    $loop = new WP_Query($args);

The output is as follows:

array(6) { ["post_type"]=> string(5) "hotel" ["p"]=> string(14) "158,67,136,153" ["posts_per_page"]=> int(20) ["orderby"]=> string(5) "title" ["order"]=> string(3) "ASC" }

So the 'p' is populated with 4 page IDs just like I wanted, except... only 1 shows up. If I change page IDs for category there is no problem and I see more.

What am I doing wrong?

1

The p parameter accepts a single integer value, not a string or array of integers.

You would want to use the post__in parameter which allows for an array of post id's. Just a few notes here:

  • You will need to check if you actually have a valid array of post ID's before passing it to post__in. If an empty array is passed, WP_Query fails epically in that it returns all posts regardless. So be very carefull with this

  • post__in will return sticky posts as well, so you would want to consider adding 'ignore_sticky_posts' => 1 to your query args

  • You will need to convert the string of post ID's to an array using wp_parse_id_list() before passing the ID's to post__in

You can probably try something like this:

$value = get_field( 'event_hotels', false );
// Check if we have a valid string
if ( $value ) {
    $post_id_array = wp_parse_id_list( $value );
    // Make sure we have a valid array of ID's
    if ( $post_id_array ) {
        $args = [
            'post__in'            => $post_id_array,
            'ignore_sticky_posts' => 1,
            // REST OF YOUR ARGS
        ];
        $loop = new WP_Query( $args );

        // Your loop

        wp_reset_postdata(); // After your loop, VERY IMPORTANT

    }
}

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.