WordPress中我们有些页面或者文章并不想让它展现在搜索结果页面,但是大部分人应该说到这个WordPress搜索排除大部分都是排除页面,很少人用于WordPress搜索排除特定文章如果要让WordPress搜索排除特定文章就需要添加相对于的配置函数,今天呢我们就说说这个与众不同的功能需求WordPress搜索排除特定文章。

WordPress搜索排除特定文章或页面


function ruikeedu_search_filter($query) {
if ( !$query->is_admin && $query->is_search) {
    $query->set('post__not_in', array(40, 9) ); // 文章或者页面的ID
}
    return $query;
}
add_filter( 'pre_get_posts', 'ruikeedu_search_filter' );

WordPress搜索排除所有页面


add_filter('pre_get_posts','search_filter');
function search_filter($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}

WordPress搜索排除某些分类


function search_filter( $query) {
if ( !$query->is_admin && $query->is_search) {
    $query->set('cat','-15,-57'); // 分类的ID,前面加负号表示排除
}
    return $query;
}
add_filter('pre_get_posts','search_filter');

WordPress搜索屏蔽


add_action('admin_init', 'ruikeedu_search_ban_key');
function ruikeedu_search_ban_key() {
    add_settings_field('ruikeedu_search_key', 'ruikeedu搜索关键词屏蔽', 'ruikeedu_search_key_callback_function', 'reading');
    register_setting('reading','ruikeedu_search_key');
}
       
function ruikeedu_search_key_callback_function() {
    echo '<textarea name="ruikeedu_search_key" rows="10" cols="50" id="ruikeedu_search_key" class="large-text code">' . get_option('ruikeedu_search_key') . '</textarea>';
}
add_action('template_redirect', 'ruikeedu_search_ban');
function ruikeedu_search_ban(){
    if (is_search()) {
        global $wp_query;
        $ruikeedu_search_key =  get_option('ruikeedu_search_key');
        if($ruikeedu_search_key){
            $ruikeedu_search_key = str_replace("\r\n", "|", $ruikeedu_search_key);
            $BanKey = explode('|', $ruikeedu_search_key);
            $S_Key = $wp_query->query_vars;
            foreach($BanKey as $Key){
                if( stristr($S_Key['s'],$Key) != false ){
                    wp_die('请不要搜索非法关键字');
                }
            }
        }
    }
}

今天要说的WordPress搜索排除特定文章就写完了,如果您还要其它的疑问欢迎咨询我们,更多WordPress教程就到文章专栏观看。