Support

Account

Home Forums Front-end Issues Post Object field with multiple posts into a WP_Query or while loop?

Helping

Post Object field with multiple posts into a WP_Query or while loop?

  • How do i get a list of posts from a field this while loop like WP_query does

    
    if ($posts_order == 'custom'):
        // post objects from field
        $posts_custom = get_field('posts_custom', 23697);
        print_r($posts_custom);
        //  what $args to use here?
        // $directors = new WP_Query($args);
        $directors = $posts_custom;
    else:
        //this all works fine.
        $args = array(
            'post_type' => 'dsv_directors',
            'nopaging'  => true,
            'meta_key'  => $posts_order,
            'orderby'   => 'meta_value',
            'order'     => $posts_order_direction,
        );
        $directors = new WP_Query($args); 
    endif;
    

    error ‘Fatal error: Uncaught Error: Call to a member function have_posts() on array in /Users/jynk/Projects/500_2AM/web/2amweb2014/wp-content/themes/2am-master/templates/content-directors.php:88’

    line 88
    $i = 0; while ($directors->have_posts()): $i++;

    any help appreciated. D.

  • Hello…

    With WP_Query you can use the argument post__in to pass in an array of post IDs…
    See here: https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

    So… with a Post Object ACF filed, you might be returning IDs or Post Objects (default).

    If returning Post Objects, you can use this code to get an array of IDs:

    
    $post_objects = get_field('po');
    $post_object_ids = array_map(function($o) { return $o->ID; }, $post_objects); // array of IDs to pass to: post__in in a WP_Query
    

    Careful though about passing an empty array to post__in because it will return all results.

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

The topic ‘Post Object field with multiple posts into a WP_Query or while loop?’ is closed to new replies.