首页 > 解决方案 > 如何仅为页面添加类别?

问题描述

我在我的 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' );

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

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

标签: phpwordpresscategories

解决方案


我可以想到两种方法。我不确定您希望它如何在存档页面和搜索页面上工作,因此第二种方法可能不适合您。

创建模板的第一个解决方案:例如 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');

推荐阅读