phpwordpressfilter

How to get posts from an array of user IDs in WordPress?


I have a array of user IDs:

$users_id_array = array('1','23','4','7')

I need to display all posts of this array.

I have tried several codes, but it does not work.

Firstly I get a array of user IDs using a recursive MySQL query, and then I apply a filter on get_posts.

add_filter( 'get_posts', 'posts_filter_by_id' );
function posts_filter_by_id( $query ) {
    global $wpdb;
    $usuarios_visibles= array();
    // This is a recursive search for get user's id. 
    $busca_usuarios_visibles = $wpdb->get_results( 
        $wpdb->prepare( "        
            SELECT * FROM wpbc_lists_father WHERE id_padre = %d
        UNION SELECT * FROM wpbc_lists_father WHERE id_padre IN 
            (SELECT id_hijo FROM wpbc_lists_father  
            WHERE id_padre = %d)", 
            get_current_user_id(), get_current_user_id()
            ) 
    );
    foreach ($busca_usuarios_visibles as $uv){array_push($usuarios_visibles, $uv->id_hijo);}
    array_push($usuarios_visibles, get_current_user_id());

$args = array(
    'posts_per_page'   => 5,
    'offset'           => 0,
    'category'         => '',
    'category_name'    => '',
    'orderby'          => 'date',
    'order'            => 'DESC',
    'include'          => '',
    'exclude'          => '',
    'meta_key'         => '',
    'meta_value'       => '',
    'post_type'        => 'post',
    'post_mime_type'   => '',
    'post_parent'      => '',
    'author'       => $usuarios_visibles,
    'author_name'      => '',
    'post_status'      => 'publish',
    'suppress_filters' => true 
);
$query = get_posts( $args ); 
    //$query->set( 'posts_per_page', 3 );
    //$query->set( 'author', $busca_usuarios_visibles);
    //$query->set( 'author', get_current_user_id());    
    return $query;
}

Solution

  • WordPress provides functionality for this already.

    Using your array as a starting point, we need to convert it to a comma separate list before passing it to the WP_Query object.

    $users_id_array = array('1','23','4','7');
    
    // Convert to comma separated list
    $user_ids = implode(',', $users_id_array);
    
    // Get all posts by these authors
    $query = new WP_Query( array( 
        'post_type' => 'post',
        'author' => $user_ids 
    ) );
    

    From here, you can loop through the $query object to display the posts.

    Alternatively, you can use author__in instead (which removes the need for implode() to get a comma separate string):

    $users_id_array = array('1','23','4','7');
    
    $query = new WP_Query( array( 
        'post_type' => 'post',
        'author__in' => $users_id_array
    ) );