How to add posts to wp_query result?

Here’s a hack for the main post query in wp-admin that should do the trick:

/**
 * Modification of the wp-admin main (post) query: 
 *     If current user has the "client" role then 
 *     show client's posts OR posts where the "client" meta value is the client id.
 *
 * @see http://wordpress.stackexchange.com/a/173967/26350
 */

function wpse_pre_get_posts( $q )
{
    if( is_admin()
        && $q->is_main_query()
        && 'post' === $q->get( 'post_type' ) 
        && ! current_user_can( 'administrator' )  
    ) 
    {
        $q->set( 'author',  get_current_user_id() );
        if( current_user_can( 'client' ) ) 
        {
            $q->set( 'author',  null );
            $q->set( 'meta_key', 'client' );
            $q->set( 'meta_value', get_current_user_id() );
            add_filter( 'posts_where', 'wpse_posts_where' );
        }
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wpse_pre_get_posts' );

where the callback for the posts_where filter is defined as:

function wpse_posts_where( $where )
{
    global $wpdb;
    remove_filter( current_filter(), __FUNCTION__ );
    return str_ireplace(
        "{$wpdb->postmeta}.meta_key",
        sprintf( 
            "{$wpdb->posts}.post_author = %d 
             OR {$wpdb->postmeta}.meta_key", 
            get_current_user_id() 
        ),
        $where
    );
}

where I assume there are no other meta queries on the main post query in wp-admin. If that’s not the case, then you should be able to refine this further.

Leave a Comment