【问题标题】:Wordpress - Search in Custom Post Type OnlyWordpress - 仅在自定义帖子类型中搜索
【发布时间】:2014-11-17 01:40:17
【问题描述】:

我有一个网站,其中包含博客和视频的自定义 post_type(命名视频)。以及附加的各种分类法(视频类别、视频标签等)

我正在尝试设置一个搜索功能来仅搜索视频分类法和另一个仅搜索博客分类法。每个页面中都会有一个搜索框来缩小结果。

这是我到目前为止所做的。

<aside id="sub-search" class="widget widget_search">
        <form class="search-form" action="http://www.studiobenna.com/jf/" method="get" role="search">
            <label>
                <span class="screen-reader-text">Search for:</span>
                <input class="search-field" type="search" name="s" value="long" placeholder="Search Videos">
            </label>
            <input type="hidden" name="post_type" value="video" />
            <input class="search-submit" type="submit" value="Search">
        </form>
    </aside>

这导致 url 以:http://example.com/?s=video&post_type=video 结尾

但这并不仅仅过滤视频分类。我有一个引用 post_type=post 用于常规博客搜索。

在 URL 中查询 Wordpress 搜索功能以仅返回一种帖子类型的正确方法是什么?我正在使用 WP Extended Search 插件以允许在右上角的搜索框屏幕搜索整个网站。

我还希望这些搜索仅限于帖子类型,但也可以拾取附加到它们的任何类别和标签(我不知道这是否是任何额外的步骤)。

我正在做的一个例子是在浏览旁边的搜索框中http://www.studiobenna.com/jf/?page_id=8。如果您在此处输入“博客”,则应该只有一个结果标题“Great Western Loop”,但其他结果会返回。

我已尝试将其添加到我的 functions.php 中:

function mySearchFilter($query) {
    $post_type = $_GET['post_type'];
    if (!$post_type) {
        $post_type = 'any';
    }
    if ($query->is_search) {
        $query->set('post_type', $post_type);
    };
    return $query;
};

add_filter('pre_get_posts','mySearchFilter');

但它不起作用。 我还尝试在 if (have_posts) 循环之前将其添加到 search.php 页面:

<?php

            if(isset($_GET['post_type'])) {
                $type = $_GET['post_type'];
                $args = array( 'post_type' => $type );
                $args = array_merge( $args, $wp_query->query );
            query_posts( $args );    
            }
        ?>

还是什么都没有。

【问题讨论】:

  • 你有没有尝试过……??
  • 是的,正是我在上面所做的。我需要知道如何使它工作。我的 search.php 中是否遗漏了某些内容,或者搜索 &post_type=video 有什么问题?

标签: wordpress search custom-post-type


【解决方案1】:

除了查询的 post_type 集之外,一切都是正确的。

这将适用于您的情况:

function mySearchFilter( $query ) {
    $post_type = $_GET['post_type'];
    if (!$post_type) {
       $post_type = 'any';
    }
    if ( $query->is_search ) {
       $query->set( 'post_type', array( esc_attr( $post_type ) ) );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'mySearchFilter' );

【讨论】:

  • 我会使用 get_query_var( 'post_type' ) 而不是 $_GET,因为它也适用于 WordPress Rewrite API,因此更好。
  • 与我所说的相关:wordpress.stackexchange.com/a/26892
猜你喜欢
  • 2021-12-23
  • 2013-12-22
  • 2014-05-20
  • 1970-01-01
  • 2012-09-14
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多