Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a partial match in Wordpress tax_query for custom taxonomy

Tags:

wordpress

We search in taxonomies for certain terms. The search phrase $search_data (in our example: 4000342) comes from a search form field.

The query looks like this and does work in general already, when the search phrase matches the terms exactly:

$search_data = 4000342;
$args =  array (
    'post_type' => 'product',
    'tax_query' => array(
          array(
              'taxonomy' => 'pa_version',
              'field' => 'slug',
              'terms' => $search_data
          )
      ),
 ); 

This search show all products with the Taxonomy term 4000342.

But there are a lot of different terms that contain the search phrase (4000342) as part of the term, for example: XC-KK-4000342-8.

We want to show all products where the taxonomy term contains the search phrase.

We tried different operators in the tax_query, but none of them seem to work in this case. How do we do a partial match using tax_query?

like image 689
Toni_Nutone Avatar asked Jan 18 '26 08:01

Toni_Nutone


1 Answers

WP_Query doesn't allow for a LIKE comparison for taxonomy searches so you will need to do 2 steps:

  1. First to get a list of all the slugs that are a partial match to your search term.
  2. Then use this list in your tax_queryto search for all slugs that are an exact match to the slugs in this list.

1. Get all slugs that are a partial match

Use get_terms to get a list of all terms that include your search term $search_data.

You don't need regex - get_terms already has an argument name__like that will perform a partial match instead of a full match.

$matching_terms = get_terms( array(
    'taxonomy' => 'pa_version',
    'fields' => 'slugs', // searches in the slug and returns an array of matching slugs
    'name__like' => $search_data, 
) );

This will return an array of all the slugs that partially match your search term, e.g. ('4000342', 'XC-KK-4000342-8', '123440003425').

(Note: get_terms doesn't returns terms that are empty by default. If you want to include empty terms, you can include 'hide_empty' => false in the arguments.)

2. Use this in your tax_query to search all slugs that are in this list

$args =  array (
    'post_type' => 'product',
    'tax_query' => array(
          array(
              'taxonomy' => 'pa_version',
              'field' => 'slug',
              'terms' => $matching_terms
          )
      ),
 ); 

See more about this and other WP__Term_Query parameters here that can be passed to get_terms

like image 150
FluffyKitten Avatar answered Jan 21 '26 04:01

FluffyKitten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!