admin管理员组文章数量:1134573
I need that when a costumer search in my page, it includes only post but I need to included 3 important pages too... It is possible.
For include only posts I have this code, but now How can include 3 pages by ID.
// Remove pages from search results
function exclude_pages_from_search( $query ) {
if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) {
$query->set( 'post_type', 'post' );
}
}
add_filter( 'pre_get_posts','exclude_pages_from_search' );'''
I need that when a costumer search in my page, it includes only post but I need to included 3 important pages too... It is possible.
For include only posts I have this code, but now How can include 3 pages by ID.
// Remove pages from search results
function exclude_pages_from_search( $query ) {
if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) {
$query->set( 'post_type', 'post' );
}
}
add_filter( 'pre_get_posts','exclude_pages_from_search' );'''
Share
Improve this question
edited Sep 14, 2023 at 11:16
Jacob Peattie
44k10 gold badges49 silver badges62 bronze badges
asked Sep 14, 2023 at 11:11
LaurapnunezLaurapnunez
11 bronze badge
1 Answer
Reset to default 0you're using $query->set('post_type', 'post');
to only include posts. What you can do is make it an array to include the post
type and those specific page IDs you want.
Here's an example code:
function custom_search_filter($query) {
if ($query->is_search() && !is_admin() && $query->is_main_query()) {
$query->set('post_type', 'post');
// Add the IDs of the pages you want to include in search results
$include_page_ids = array(1, 2, 3); // Replace these with your actual page IDs
// Fetch current 'post__in' query var, if any
$post_in = $query->get('post__in');
// Merge existing 'post__in' with our page IDs
if (is_array($post_in)) {
$query->set('post__in', array_merge($post_in, $include_page_ids));
} else {
$query->set('post__in', $include_page_ids);
}
}
}
add_action('pre_get_posts', 'custom_search_filter');
The custom_search_filter
function is added to the pre_get_posts
action. Within the function, it's checking if the query is a main search query that's not within the admin area. If so, it sets the post type to 'post' and specifies the IDs of the pages you want to include in an array.
With this, you'd get mostly posts in your search results, plus those three key pages you want to include. Just plug in the correct page IDs in place of 1, 2, 3 and you should be good to go!
本文标签: functionsExclude in search post and include only 3 pages
版权声明:本文标题:functions - Exclude in search post and include only 3 pages 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736802128a1953534.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论