Rubayat Nasir
Rubayat Nasir

Reputation: 1

WordPress Search for custom taxonomy field

I have two post types, Authors and Books. There is a custom taxonomy named 'Genre' in 'Books' post type . I am trying to add custom search functionality. It's working well with the rest(like - keyword, authors etc) except the custom taxonomy - Genre. Here is my code. Anyone can help please?

`<?php 
class Search {

public function __construct() {
    add_action( 'pre_get_posts', [ $this, 'posts_filter' ] );
}

public function posts_filter( $query ) {
    if ( is_admin() || ! $query->is_main_query() || ! is_search() ) {
        return $query;
    }

    $meta_query = [
        'relation' => 'OR',
            [ 
                'key' => '_book_author',
                'value' => $query->query['s'],
                'compare' => 'LIKE',
            ],
        ];

             $tax_query = [
            [
                'taxonomy' => 'genre',
                'field' => 'slug',
                'terms' => $query->query['s'],
                'operator' => 'LIKE',
            ],
        ];


        $query->set('meta_query', $meta_query);
        $query->set('tax_query', $tax_query);
        $query->set( 'post_type', 'books' );


   }
}






`

Upvotes: 0

Views: 7

Answers (0)

Related Questions