我正在开发一个 WordPress 项目,我需要在多个帖子类型和分类法中执行搜索,然后显示组合结果。我为每个帖子类型和分类创建了单独的 WP_Query 对象,检索每个查询返回的帖子的 ID,并将它们合并到一个数组中。但是,我在使用组合 ID 创建最终 WP_Query 对象时遇到了问题。
到目前为止我已经尝试过了,但没有任何结果。
function data_fetch() {
check_ajax_referer('data_fetch_nonce', 'security');
$keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : '';
$page_query = new WP_Query(array(
'fields' => 'ids',
'posts_per_page' => -1,
's' => $keyword,
'post_type' => 'page',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'page_category',
'field' => 'slug',
'terms' => 'zabiegi',
),
),
));
// Query for your custom post type
$custom_post_type_query = new WP_Query(array(
'fields' => 'ids',
'posts_per_page' => -1,
's' => $keyword,
'post_type' => 'uslugi', // Replace with your custom post type slug
'post_status' => 'publish',
));
// Concatenate posts arrays
$combined_posts = array_merge($page_query->posts, $custom_post_type_query->posts);
// Create final query
$combined_results = new WP_Query(array(
'post__in' => $combined_posts,
));
// Merge the results
$combined_results = new WP_Query();
if ($combined_results->have_posts()) {
echo '<div class="search-results">';
while ($combined_results->have_posts()) {
$combined_results->the_post();
echo '<div class="search-result-item">';
echo '<div class="search-result-wrapper d-flex">';
echo '<div class="result-content">';
echo '<p class="result-title"><a class="p c-heading" href="' . esc_url(get_permalink()) . '">' . get_the_title() . '</a></p>';
echo '</div>';
echo '</div>';
echo '<div class="result-action">';
echo '<a class="result-content p c-heading f-500" href="' . esc_url(get_permalink()) . '">Przejdź' . '<svg class="result-mini-icon c-def" width="16" height="16" viewBox="0 0 16 16">
<use xlink:href="#arrow-down-tiny"></use>
</svg></a>';
echo '</div>';
echo '</div>';
}
echo '</div>';
wp_reset_postdata();
} else {
echo '<p class="no-results">Nie znaleziono zabiegu.</p>';
}
wp_die();
}
但是,最终的查询似乎没有返回预期的结果。谁能帮助我理解我做错了什么,或者建议一种更好的方法来组合和查询 WordPress 中多个 WP_Query 对象的搜索结果?
您可以使用带有 UNION 子句的多个查询
例如:
global $wpdb;
$result = $wpdb->get_results("(SELECT ID from wp_posts p WHERE p.post_type = 'post') UNION (SELECT ID from wp_posts p WHERE p.post_type = 'page')", OBJECT);