WordPress搜索查询 - 元查询和自定义字段

4

请问大家一个问题。我在我的搜索页面模板上运行了当前的查询,如果我的搜索查询似乎包含在文章标题中,它似乎运作良好,但是当我包含一个meta查询以尝试在另一个地方查找搜索词时,它不会收集任何结果,仅显示先前的相同结果。

第二个问题是,由于某种原因它仍然只显示6篇文章(在WP管理中设置的文章数量),并且没有听取查询条件。

       <?php // WP_User_Query arguments
        $search_term = get_search_query();
        $args = array (
            'post_type' => 'courses',
            'order' => 'ASC',
            'orderby' => 'title',
            'posts_per_page' => -1,
            'nopaging' => true,
            's' => '*'.$search_term.'*',
            'meta_query' => array(
                array(
                    'key' => 'course_id',
                    'value' => $search_term,
                    'compare' => 'LIKE'
                )
            )
        );

        $wp_course_query = new WP_Query($args);
        // Get the results
        $courses = $wp_course_query; ?>

        <?php // Check for results
        if (!empty($courses->get_posts())) { ?>
                <ul class="course-list">


                <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
                 <li> <?php the_title(); ?> </li>
                <?php endwhile; endif; wp_reset_query(); ?>

            </ul>
        <?php } else { ?>
            <p>No courses match that query</p>
        <?php } ?>

我尝试过的事情:

  • 手动编码值,但没有结果。
  • 从 's' 中删除*。

尝试使用 var_dump( $wp_course_query->request ); 查看 WP 生成的确切查询。也许您需要通过 WP 过滤器修改查询以满足您的需求。 - pbaldauf
1个回答

3

在WordPress中似乎不可能做到这一点,所以我不得不用另一种方式来实现。

        $search_term = get_search_query();
        $args = array (
            'post_type' => 'courses',
            'order' => 'ASC',
            'orderby' => 'title',
            'posts_per_page' => -1,
            'nopaging' => true,
            's' => $search_term
        );
        $args2 = array (
            'post_type' => 'courses',
            'posts_per_page' => -1,
            'nopaging' => true,
            'meta_query' => array(
                 array(
                    'key' => 'course_id',
                    'value' => $search_term,
                    'compare' => 'LIKE'
                 )
              )
        );

        $courses1 = get_posts($args);
        $courses2 = get_posts($args2);
        $merged = array_merge($courses1, $courses2);
        $post_ids = array();
        foreach ($merged as $item) {
            $post_ids[] = $item->ID;
        }

        $unique = array_unique($post_ids);

        $posts = get_posts(array(
            'post_type' => 'courses',
            'order' => 'ASC',
            'orderby' => 'title',
            'post__in' => $unique,
            'posts_per_page' => -1
        )); ?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接