我们在分类学中搜索特定的术语。搜索短语$search_data (在我们的示例中是: 4000342)来自一个搜索表单字段。
当搜索短语与术语完全匹配时,查询看起来是这样的,并且通常已经起作用了:
$search_data = 4000342;
$args = array (
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_version',
'field' => 'slug',
'terms' => $search_data
)
),
); 此搜索显示所有具有分类法术语4000342的产品。
但是有许多不同的术语包含搜索短语(4000342)作为术语的一部分,例如: XC-KK-4000342-8。
我们希望显示所有产品,其中的分类法术语包含搜索短语。
我们在tax_query中尝试了不同的操作符,但在这种情况下,它们似乎都不起作用。如何使用tax_query进行部分匹配?
发布于 2020-06-17 20:31:24
WP_Query不允许对分类法搜索进行LIKE比较,因此您需要执行两个步骤:
tax_query中使用这个列表来搜索与这个列表中的鼻涕虫完全匹配的所有弹头。1.获取所有部分匹配的
使用get_terms获取包含搜索项$search_data的所有术语的列表。
您不需要regex - get_terms已经有了一个参数name__like,它将执行部分匹配而不是完全匹配。
$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,
) );这将返回一个数组的所有子弹,部分匹配你的搜索词,例如('4000342', 'XC-KK-4000342-8', '123440003425')。
(注意: get_terms不返回默认为空的条件。如果要包含空项,可以在参数中包括'hide_empty' => false。)
tax_query 2.在中使用它搜索列表中的所有弹头
$args = array (
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_version',
'field' => 'slug',
'terms' => $matching_terms
)
),
); 请参阅更多有关此和其他可传递给这里的查询参数的get_terms的信息。
发布于 2020-06-17 13:58:37
你可以用正则表达式来做。首先,你需要得到所有的条件:
$terms = get_terms( array(
'taxonomy' => 'pa_version',
'field' => 'slug',
) );然后得到regex结果:
$filtered_terms = preg_grep('/' . $search_data . '/gm', $terms);并在您的税务查询中使用:
$args = array (
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_version',
'field' => 'slug',
'terms' => $filtered_terms
)
),
); 希望这能有所帮助。
发布于 2020-06-17 12:54:37
您需要使用关系' or‘来显示来自两个分类法或关系的产品,以及用于用两个分类法显示产品,如下所示:
$args = array (
'post_type' => 'product',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'pa_version',
'field' => 'slug',
'terms' => 4000342,
),
array(
'taxonomy' => 'pa_version',
'field' => 'slug',
'terms' => 'XC-KK-4000342-8',
)
),
); https://stackoverflow.com/questions/62429157
复制相似问题