首页 文章

Wordpress - 仅在自定义帖子类型中搜索

提问于
浏览
0

我有一个带博客的网站和一个自定义的视频post_type(命名视频) . 随附的各种分类法(视频类别,视频标签等)

我正在尝试设置一个搜索功能来搜索视频taxononmy和另一个搜索只是博客分类 . 每个页面中都会有一个搜索框,以减少结果 .

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

<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的常规博客搜索 .

What is the correct way to query the Wordpress search function in the URL to only return one post type? 我正在使用WP扩展搜索插件,允许screem右上角的搜索框搜索整个网站 .

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

我正在做的一个例子是在浏览旁边的搜索框中的http://www.studiobenna.com/jf/?page_id=8 . 如果您在此处输入博客,则应该只有一个结果 Headers "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 );    
            }
        ?>

依然没有 .

1 回答

  • 0

    除了查询的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' );
    

相关问题