對於一般的WordPress部落格主題,首頁都是調用最新的文章列表,如果我們希望在首頁排除某些分類,該如何操作呢?最簡單的方法就是通過 pre_get_posts 鉤子來改變主查詢。下面就是一個很好的例子,將代碼添加到你主題的 functions.php 文件中:
1 2 3 4 5 6 7 8 |
function exclude_category_home( $query ) { if ( $query->is_home ) { $query->set( 'cat', '-4, -23' ); } return $query; } add_filter( 'pre_get_posts', 'exclude_category_home' ); |
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( ‘cat’, ‘-4, -23’ );
}
return $query;
}
add_filter( ‘pre_get_posts’, ‘exclude_category_home’ );
註意根據自己的需要,修改代碼的第 3 行中的分類ID,比如你想排除分類 6 和 9,就將第 3 行改為:
1 |
$query->set( 'cat', '-6, -9' ); |
$query->set( ‘cat’, ‘-6, -9’ );
就這麼簡單。
如果你不希望在頂部顯示置頂文章,可以在第 3 行下面添加:
1 |
$query->set( 'ignore_sticky_posts', '1' ); |
$query->set( ‘ignore_sticky_posts’, ‘1’ );
如果出現新文章跑到最下面,老文章在上面(也就是倒過來瞭),那試試添加:
1 2 |
$query->set( 'orderby', 'date' ); $query->set( 'order', 'DESC' ); |
$query->set( ‘orderby’, ‘date’ );
$query->set( ‘order’, ‘DESC’ );
擴展閱讀:如何創建WordPress自定義查詢