phpsqlwordpresswoocommerce

Enable custom taxonomy and product_tag in WooCommerce product search


I'm hoping that one of you geniuses can help me.

I have a site: https://lifesourcebookshop.co.uk/ that I want to modify the WooCommerce product search on.

What I want: To modify the query of the WooCommerce search form (in frontend) to display the products by searching in the name, description, product_tag and a custom taxonomy called book_author of the products.

What I have: I've tried with this code inspired from this answer that returns results for the name and description of the product. But if I search with the tag names or the book author, then the results aren't correct.

How to reproduce this issue (put the code below in functions.php file of your active theme):

add_filter('posts_search', 'woocommerce_search_product_tag_extended', 999, 2);
function woocommerce_search_product_tag_extended($search, $query) {
    global $wpdb, $wp;
    $qvars = $wp->query_vars;
    if (is_admin() || empty($search) ||  !(isset($qvars['s']) && isset($qvars['post_type']) && !empty($qvars['s']) && $qvars['post_type'] === 'product')) {
        return $search;
    }
    $taxonomies = array('product_tag', 'book_author');
    $tax_query  = array('relation' => 'OR');
    foreach($taxonomies as $taxonomy) {
        $tax_query[] = array(
            'taxonomy' => $taxonomy,
            'field'    => 'name',
            'terms'    => esc_attr($qvars['s']),
        );
    }
    $ids = get_posts(array(
        'posts_per_page'  => -1,
        'post_type'       => 'product',
        'post_status'     => 'publish',
        'fields'          => 'ids',
        'tax_query'       => $tax_query,
    ));
    if (sizeof($ids) > 0) {
        $search = str_replace('AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $ids ) . ")) OR (", $search);
    }
    return $search;
}

Example: If you search for murphy (an author) - https://lifesourcebookshop.co.uk/?s=murphy&post_type=product then it only shows 2 products. However, if I look at the archive for that author (https://lifesourcebookshop.co.uk/book_author/abigail-murphy/), then there are actually 5 books.

I'm hoping you can help.

Thanks, Rob


Solution

  • I've resolved this by installing Search Everything.

    Rob