让WordPress的搜索结果包括自定义文章类型的内容

如果你的WordPress站点添加了自定义文章类型,请记得让WordPress默认搜索支持自定义文章类型,即可以搜索自定义文章类型的内容。实现的方法很简单,将下面的代码添加到主题的functions.php 文件中即可:

1
2
3
4
5
6
//让搜索支持自定义文章类型
function searchAll( $query ) {
  if ( $query->is_search ) { $query->set( 'post_type', array( 'post','books', 'product','works' )); } 
  return $query;
}
add_filter( 'the_search_query', 'searchAll' );

//让搜索支持自定义文章类型
function searchAll( $query ) {
if ( $query->is_search ) { $query->set( ‘post_type’, array( ‘post’,’books’, ‘product’,’works’ )); }
return $query;
}
add_filter( ‘the_search_query’, ‘searchAll’ );

注意根据自己的实际修改第 3 行数组(array)中的文章类型别名。

或者也可以将下面的代码添加到当前主题的 functions.php 文件中:

以下代码的功能:让搜索结果支持所有自定义文章类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//让搜索支持所有自定义文章类型
function include_post_types_in_search($query) {
	if(is_search()) {
		$post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
		$searchable_types = array();
		if($post_types) {
			foreach( $post_types as $type) {
				$searchable_types[] = $type->name;
			}
		}
		$query->set('post_type', $searchable_types);
	}
	return $query;
}
add_action('pre_get_posts', 'include_post_types_in_search');

//让搜索支持所有自定义文章类型
function include_post_types_in_search($query) {
if(is_search()) {
$post_types = get_post_types(array(‘public’ => true, ‘exclude_from_search’ => false), ‘objects’);
$searchable_types = array();
if($post_types) {
foreach( $post_types as $type) {
$searchable_types[] = $type->name;
}
}
$query->set(‘post_type’, $searchable_types);
}
return $query;
}
add_action(‘pre_get_posts’, ‘include_post_types_in_search’);

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号