php - 将两个单独的 wp 查询合并为一个查询以进行搜索
问题描述
我目前在我的类别页面上有一个搜索栏,可以搜索产品标题(自定义帖子类型)或品牌分类。我可以让这两个独立工作,将任一参数传递给 WP_Query,但是如果我尝试将它们合并在一起,则两者都不起作用。
我所拥有的是:
$search = sanitize_text_field($_POST['productsearch']);
$post_category = $_POST['post_cat'];
$cats = array(
'taxonomy' => 'productscat',
'field' => 'id',
'key' => 'name',
'terms' => $post_category,
);
$args = array(
'post_type' => 'products', //custom post type
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC',
's' => $search,
'tax_query' => $cats,
'posts_per_page' => -1,
);
$args2 = array(
'post_type' => 'products', //custom post type
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'brands',
'field' => 'slug',
'terms' => $search,
),
),
'posts_per_page' => -1,
);
$merged = array_merge($args, $args2);
$search_query = new WP_Query($merged);
if ($search_query->have_posts()) :
以此类推;那么我在合并参数中缺少什么?
本质上,我's' => $search
只在其中一个数组中使用来搜索帖子名称,我在品牌分类数组中不需要(或相信我需要)
解决方案
您可以像这样组合查询。您可以添加多个tax_query
.
$search = sanitize_text_field($_POST['productsearch']);
$post_category = $_POST['post_cat'];
$args2 = array(
'post_type' => 'products', //custom post type
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC',
's' => $search,
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'brands',
'field' => 'slug',
'terms' => $search
),
array(
'taxonomy' => 'productscat',
'field' => 'id',
'terms' => $post_category
)
)
);
$search_query = new WP_Query( $args2 );
if ( $search_query->have_posts() ) :
endif;
推荐阅读
- html - 当每个字母都用 span 包裹时,Chrome 会打断单词
- flutter - 自定义照片查看器裁剪图像
- javascript - 在 Javascript 中过滤对象
- scala - 将 sql 转换为数据框 api
- python - 如何使用 cppyy 嵌入 Python 而不是 boost-python
- python - 如果几列是空白或空的,如何获取提取的行
- google-bigquery - BiqQuery 在基于日期排序时不考虑月份
- java - 如何重构输入参数的嵌套修改?
- android - 错误 运行子进程 ionic cordova build 时发生错误
- google-apps-script - 将数据从 json 文件加载到 Google 工作表