WP_Query can’t exclude more than 1 author?

It seem wp_query have the problem where it does not accept more than 1 negative value in author argument. for example:

$args = array('author=-2,-3,-4'); 
$newquery = WP_Query($args); 

This grab everything else. Simply doesn’t work.

Read More

I found this trac, but seem still no official patch for this.

Any suggestion?

Related posts

Leave a Reply

4 comments

  1. You are right, it is not possible to pass an array with author IDs to exclude them. The reason is in wp-includes/query.php at line 2294 – 2298

    if ( strpos($q['author'], '-') !== false ) {
      $eq = '!=';
      $andor = 'AND';
      $q['author'] = explode('-', $q['author']);
      $q['author'] = (string)absint($q['author'][1]); // this line select the first ID and only this ID
    } else {
      $eq = '=';
      $andor = 'OR';
      }
    

    You have to get all author IDs, then exclude the unwanted authors and request the posts from the remaining authors

    // array for user IDs
    $users   = array();
    
    // roles to include
    $roles   = array( 'author', 'editor', 'contributor', 'administrator', 'superadmin' );
    
    // user IDs to exclude
    $exclude = array( 2,3,5 );
    
    // get all users
    $_users = get_users();
    
    foreach ( $_users as $user ) {
    
        // do not add the user ID if the users role does not match or the users ID is excluded
        if ( in_array( $user->ID, $exclude ) || ! in_array( $user->roles[0], $roles ) )
            continue;
    
        // add user
        array_push( $users, $user->ID );
    
    }
    
    $args = array('author=' . implode( ',', $users ); 
    $newquery = WP_Query( $args );
    
  2. I didn’t realize it before, but it seems that you currently can’t exclude multiple authors posts using WP_Query, I’ve updated the Codex to be less misleading.

    Here is a way to exclude posts from multiple authors using the $wpdb class:

    <?php
    
       $results = $wpdb->get_results(
       "Select * FROM $wpdb->posts
       WHERE post_type = 'post'
       AND post_status = 'publish'
       AND post_author <> 2
       AND post_author <> 3", 
       OBJECT
       );// gets posts, that are published, and exclude posts written by authors 2 and 3
    
       foreach($results as $result)
       {
       echo "<h2>".$result->post_title."</h2>";
       }
    

    ?>

  3. “UNTESTED” but could you do it this way?

     function filter_pre_get_posts( $query ) {
    
    // If this is the blog posts index,
    // and if this is the main query,
    
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'author', -2,-3,4);
        }
     }
     add_action( 'pre_get_posts', 'filter_pre_get_posts' );
    

    This is a function I picked up here for excluding categories. Not sure if it could be used to exclude by author but it is far better than writing a custom query if it works