如何使用 Wordpress 挂钩将 2 个查询结果合并为一个

问题描述 投票:0回答:1


我对Wordpress很陌生,最近我发现了这个问题,这花了我很多时间来理解,但我仍然不知道如何解决它。
我正在使用 Wordpress 基本搜索,使用经典的 search.php
我需要根据他们的 post_title OR 他们的 自定义字段分类法 检索 POSTS,例如我的案例分类法是“color”,使用 ACF 我添加了一个名为 synonimes 的新字段,它是中继器字段,内部有 N* 个文本字段,称为 synonim
基本上,我需要使用 synonimes 匹配和 post_title 匹配 (基本上是 WordPress 查询参数中的经典 's' => $value) 检索两个帖子,使用钩子 pre_get_posts 我只达到了我可以的程度使用 AND 条件过滤 POSTS,这确实是错误的。
我不知道如何改变这种行为,我放弃了这种方式,我现在尝试将我找到的结果与钩子中的主查询合并。
我现在在这里使用此代码:

function filter_tax($query){
if (!is_admin() && $query->is_main_query() && $query->is_search()) {

    $args_new_query = array(
        'post_type' => MAIN_POST,
        'posts_per_page' => 12,
        'post_parent' => 0,
    );

    $new_query = new WP_Query($args_new_query);

    $search_keyword = sanitize_text_field(get_search_query());

    $matching_posts = array();

    if ($new_query->have_posts()) {
        $taxonomy_name = 'color';

        while ($new_query->have_posts()) : $new_query->the_post();
            $post_id = get_the_ID();

            $terms = wp_get_post_terms($post_id, $taxonomy_name);

            foreach ($terms as $term) {
                $synonim_values = get_field('synonimes', $taxonomy_name . '_' . $term->term_id);

                if (is_array($synonim_values)) {

                    foreach ($synonim_values as $syn) {
                        if (strpos($syn['synonim'], $search_keyword) !== false) {
                            $matching_posts[] = get_post($post_id);
                            break 2;
                        }
                    }
                }
            }
        endwhile;
        wp_reset_postdata();
    }

    if (!empty($matching_posts)) {
        /*$query->set('post__in', wp_list_pluck($matching_posts, 'ID'));*/
        $query->posts = array_merge([], $matching_posts);
    }
}
}

不幸的是,在我的模板中,我只能对基本搜索帖子进行分页,而我的$matching_posts丢失了并且无法检索,它看起来很简单,但仍然花费了我很多时间。

php wordpress search hook advanced-custom-fields
1个回答
0
投票

我由于误解了POST__IN的内部功能而犯了一个错误。
最初我以为我可以通过他们的 ID inject POSTS,但这是错误的,因为我是通过他们的 ID 过滤 POSTS
所以我想出了这个:

$args_basic = [
        'post_type' => $contentList,
        'numberposts' => -1,
        'post_parent' => 0,
        's' => $_GET['s'],
    ];

    $prev_search = get_posts($args_basic);
    $prev_search_ids = array_map(fn($item) => $item->ID, $prev_search);
    $query->set('post_type', $contentList);

    if (!empty($matching_posts)) {
        $ids_serach = array_merge($prev_search_ids, wp_list_pluck($matching_posts, 'ID'));
        $query->set('post__in', $ids_serach);
        $query->set('s', '');
    }

这是正确的使用方法POST__IN
我将我的问题和答案留在这里,以防您也有同样的情况,不要浪费时间合并查询帖子!它永远不会起作用

© www.soinside.com 2019 - 2024. All rights reserved.