我有一个带有博客和视频的自定义 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扩展搜索插件来允许屏幕右上角的搜索框搜索整个网站。
我还希望这些搜索仅限于帖子类型,但也选择附加到它们的任何类别和标签(我不知道这是否是任何额外的步骤)。
我正在做的一个例子在这里 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 );
}
?>
还是什么都没有。
除了查询的 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' );