如何只为页面添加类别?

问题描述

我已在我的functions.PHP文件添加了此功能,以显示wordpress页面的类别选项。很好。

function support_category_for_pages() {  
    // Add category support to pages
    register_taxonomy_for_object_type('category','page');  
}
add_action( 'init','support_category_for_pages' );

但是是否可以仅显示/限制页面的某些类别(它们不能出现在帖子下)?

我希望我写的正确。基本上,要求是为帖子和页面保留不同的类别,并且它们不应出现在彼此的类别选项中。

解决方法

我可以考虑两种方法。我不确定您希望它在存档页面和搜索页面上如何工作,因此第二种方法可能对您不起作用。

第一个创建模板的解决方案: 例如category-news.php

您可以在内部针对该类别专门修改查询

$args = array(
'post_type' => 'posts'
//add more arguments if needed
);

$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
      $the_query->the_post();
      // Do Stuff
    } // end while
} // endif

// Reset Post Data
wp_reset_postdata();

使用pre_get_posts的第二个解决方案:

 function wp50_exclude_post_type_pages() {
 //in the array you can add ids,slugs or names
 if ( is_category( array( 9,'cat2','Category 3' )) && $query->is_main_query() ) {
   //here we tell the query to show posts type only 
   $query->set( 'post_type','posts' );
   return $query;
 }
 
}
add_action( 'pre_get_posts','wp50_exclude_post_type_pages');