0
votes

I am using woocommerce. In short I need to find products where attributes term value should be "LIKE" 100 value. So it should find terms like: 100/104, 100/99.

My URL search: domain.com/?pa_boltpcd=100

So I have attribute (pa_boltpcd) which is a taxonomy. This taxonomy (pa_boltpcd) has terms:

100
100/104
100/99 

At the moment it only shows products where term value is exactly "100". Why where is no such operator "like" which could find all these 3 terms by searching for "100" value.

What I tried:

function taxonomy_like( $q ) {

if(isset($q->query['pa_boltpcd'])){

    $tax_query = (array) $q->get( 'tax_query' );

    $termIds = get_terms([
        'name__like' => '100',
        'fields' => 'ids'
    ]);

    $tax_query[] = array(
        'taxonomy' => 'pa_boltpcd',
        'field' => 'term_id',
        'terms' => $termIds,
        'operator' => 'IN'
    );

    $q->set( 'tax_query', $tax_query );
}

}
add_action( 'woocommerce_product_query', 'taxonomy_like' );
  1. With this hook first I am searching for terms where is value 100 with criteria 'LIKE', so it will find all these terms.

  2. Then I collect found terms id's.

  3. After that I am creating tax_query where it could search by my founded id's.

BUT the problem is that it returns the same result, and it shows products where term is exactly is 100 ...

Please give me some tips what to do??? Sorry for bad english, correct me where is not clear.

1

1 Answers

0
votes

As in a tax query you can query an array of terms, it doesn't handle LIKE with wildcard character %, like in SQL. Hopefully get_terms() does this when using 'name__like'

The product attribute checkbox option "Enable Archives?" need to be disabled.

To test the following code I have first added your product attribute "boltpcd" to Woocommerce with 3 terms 100, 100/104 and 100/99. Then I have set the attribute in 3 different products with for each one a different term. For me it works and display the 3 products, when adding ?pa_boltpcd=100 to the shop url.

I have made very small changes to your code using a similar hook that targets tax query:

add_filter( 'woocommerce_product_query_tax_query', 'custom_taxonomy_like', 10, 2 );
function custom_taxonomy_like( $tax_query, $query ) {
    $taxonomy = 'pa_boltpcd';

    if( ! isset($_GET[$taxonomy]) )
        return $tax_query;

    // The tax query
    $tax_query[] = array(
        'taxonomy' => $taxonomy,
        'field' => 'term_id',
        'terms' => get_terms([ // Get terms "%LIKE%"
            'name__like' => esc_attr( $_GET[$taxonomy] ),
            'fields' => 'ids',
            'taxonomy' => $taxonomy
        ])
    );

    return $tax_query;
}

Code goes in function.php file of your active child theme (or active theme). tested and works.

I get the 3 products which have each one a different term set for pa_boltpcd taxonomy (100, 100/104 and 100/99):

enter image description here