简体   繁体   中英

How to show search results from specific category in the end in WordPress

I am trying to move the posts in specific category (uncategorized) in the end of the search results in WordPress frontend search page.

The approach which I have for now is:

  1. Remove the posts from the selected category from the main query
  2. Create a new query and get posts from that category only
  3. Merge both query results, so now the results from the specified category are in the end
  4. Have to maintain pagination too

The code I am using for step 1 is:

function wcs_exclude_category_search( $query ) {
    if ( is_admin() || ! $query->is_main_query() )
      return;

    if ( $query->is_search ) {
      $query->set( 'cat', '-11' );
    }

  }
  add_action( 'pre_get_posts', 'wcs_exclude_category_search', 1 );

Any guidance for this approach or a better approach would be appreciated. Thanks.

Normally I would prefer the "tax_query" parameter, something like

// in case there are other tax_query clauses on the query
$tax_query = (array) $query->get( 'tax_query' );
$tax_query[] = [
    'taxonomy' => 'category',
    'terms'    => 11,
    'field'    => 'term_id',
    'operator' => 'NOT IN'
];
$query->set( 'tax_query', $tax_query ); 

On the other hand, if the query already has posts from the "uncategorized" category, you could sort the results just before display by hooking on the_posts , something like:

add_action( 'the_posts', function( $posts, $query ){
    if ( ! $query->is_search() ) {
        return $posts;
    }
    usort( $posts, function ( $a, $b ){
        $a_in_uncategorized = has_term( 11, 'category', $a );
        $b_in_uncategorized = has_term( 11, 'category', $b );
        // if neither or both are on the "uncategorized" category
        // sort by date or whatever
        if ( $a_in_uncategorized === $b_in_uncategorized ) {
             return $b->post_date <=> $a->post_date;
        }
        if ( $a_in_uncategorized && ! $b_in_uncategorized )  {
             return 1;
        }
        if ( ! $a_in_uncategorized && $b_in_uncategorized )  {
             return -1;
        }
        return 0;
    } );
    return $posts;
}, 10, 2 );

I hope that helps :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM