wordpress 排除指定文章分類

有的時候,需要創建某個測試文章分類,比如“測試1”、“測試2”,它們的ID分別爲13、14,這兩個分類下的文章只供特定情況下使用,故在首頁、搜索頁面、分類目錄等欄目都不想顯示該分類下及該分類下的文章,就需要在查詢的時候排除該分類及該分類下的文章。

分類目錄下排除該文章分類

在functions.php中加入以下代碼

function exclude_categories( $query ) {
    $query['exclude'] = '-13,-14';
    return $query;
}
add_filter( 'widget_categories_args', 'exclude_categories' );

搜索結果排除該分類的文章

在functions.php中加入以下代碼

function exclude_search_category( $query) {
    if ( $query->is_search) {
        $query->set('cat','-13,-14'); 
    }
    return $query;
}
add_filter('pre_get_posts','exclude_search_category');

首頁文章列表排除該分類的文章

在functions.php中加入以下代碼

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-13, -14' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );

統計文章總數排除該分類

在functions.php中加入以下代碼

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-13, -14' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );

使用wordpress內置函數調用

<?php
    $posts = get_posts( 'numberposts=-1' );
    echo count($posts);
?>

 方法二:

如果你要在首頁顯示的日誌排除某個特定的分類,如何操作呢?下面的代碼就是排除 13 和 26 這兩個分類的日誌。

 

<?php if ( have_posts() ) : query_posts($query_string .'&cat=-13,-26'); while ( have_posts() ) : the_post(); ?>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章