0

I am unsetting the query var author_name for querying posts in the author template page. I am using pre_get_posts to filter the main query.

After the query is run, I need to set back the author_name query var.

This is where I unset it.

function wpquery( $query )
     if ( $query->is_author() && $query->is_main_query()) {
                $query->set( 'post_status', $post_status );
                unset( $query->query_vars['author_name'] ); 
                $tax_query = array(  
                    array(
                        'taxonomy' => 'tax',
                        'field' => 'name',
                        'terms' => $var
                    )
                );
                $query->set( 'tax_query', $tax_query );
        }   
add_action( 'pre_get_posts', 'wpquery' );

After the query runs, i have to set author_name

2

An easy way is to use a static variable to store author name, then run again same function on a later hook, maybe 'posts_results' and set back the variable:

function wpquery( $query, $query_on_results = NULL ) {
  static $author_name = NULL;
  if ( current_filter() === 'pre_get_posts' ) {
    if ( $query->is_author() && $query->is_main_query() ) {
      $query->set( 'post_status', $post_status );
      $author_name =  $query->query_vars['author_name'];
      unset( $query->query_vars['author_name'] ); 
      $tax_query = array(  
        array(
         'taxonomy' => 'tax',
         'field' => 'name',
         'terms' => $var
        )
      );
      $query->set( 'tax_query', $tax_query );
    } 
  } elseif ( current_filter() === 'posts_results' ) {
    if ( $query_on_results->is_main_query() && ! empty( $author_name ) ) {
      $query_on_results->query_vars['author_name'] = $author_name;
      $author_name = NULL;
      remove_filter( current_filter(), __FUNCTION__, 20, 2 );
    }
    // $query represent the 1st arg passed to function, that on posts_result hook
    // is the retrieved posts array. Always return it as is to do not alter results
    return $query;
  }
}   

add_action( 'pre_get_posts', 'wpquery' );

add_filter( 'posts_results', 'wpquery', 20, 2 );
  • I found a problem when unsetting author_name. Author pages with no posts will return a 404 page. Is there a way to fix this? – Gixty May 23 '14 at 22:35

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.