2025-04-22

如果你的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’);

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *