问题
如何修改此代码以不显示我们刚刚添加的新类别中的帖子。
我在这个网站上搜索了其他类似的答案[例如:Exclude category on blog list page ] 但不知道如何在我的项目中将其转换为可用代码。
背景
我们有不同的页面显示最近帖子的链接。在主博客页面上,我们需要隐藏指向5个不同类别帖子的链接。
代码-第页
<ul>
<?php
if (isset($_GET[\'tag\'])):
$tagparam = filter_var($_GET[\'tag\'], FILTER_SANITIZE_STRING);
endif;
$postslist = get_regular_posts_query(\'25\',\'\',$tagparam);
while ( $postslist->have_posts() ) {
$postslist->the_post();
?>
代码-功能。php
// Get Non-Featured Posts using WP_QUERY
function get_regular_posts_query($numberposts,$categoryName=NULL,$tagName=NULL){
$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
$args = array(
\'posts_per_page\' => $numberposts,
\'post_status\' => \'publish\',
\'category_name\' => $categoryName,
\'post_type\' => \'post\',
\'orderby\' => \'post_date\',
\'tag\' => $tagName,
\'meta_query\'=>array(
\'relation\'=>"OR",
array(
\'key\' => "featured_post",
//\'value\' => "featured",
\'compare\' => "NOT EXISTS"
),
array(
\'key\' => "featured_post",
\'value\' => "",
\'compare\' => "="
)
),
\'paged\' => $paged,
);
$posts = new WP_Query( $args );
if(! $posts ) {
//throw new Exception("NoSuchPost");
echo "No Articles Found!";
}
return $posts;
}
从我做的其他研究中,我发现必须输入类别的ID。我的是:89、90、91、92、93。
SO网友:hwl
方法given in the WPSE answer you linked 当当前查询是主页博客页面(不是存档页面或类别页面等)时,将从数组中按ID列出的类别中排除帖子。它也不会影响页面上的辅助查询。放置在函数中。php的主题,它应该做到这一点。
修改了注释并添加了5个cat ID:
function my_exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
//check it is home blog page and the query is main query, not a secondary query
$query->set( \'category__not_in\', array( 89, 90, 91, 92, 93 ) );
//adds this query var to home page main query
}
}
add_action( \'pre_get_posts\', \'my_exclude_category\' );
//this is hooked right before query
有关的详细信息
Wp_Query
class category args ||
pre_get_posts()
action hook改为添加category__not_in
参数设置为$args
包含的函数数组:
$args = array(
\'posts_per_page\' => $numberposts,
\'post_status\' => \'publish\',
\'category__not_in\' => array( 89, 90, 91, 92, 93 ),
\'post_type\' => \'post\',
\'orderby\' => \'post_date\',
...(etc)