【问题标题】:How to add categories for pages only?如何仅为页面添加类别?
【发布时间】:2020-09-03 17:31:40
【问题描述】:

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

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

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

【问题讨论】:

    标签: php wordpress categories


    【解决方案1】:

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

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

    【讨论】:

    • 刚试过这个和网站(generatewp.com/taxonomy),但没有成功。感谢您尝试帮助。
    • 好吧,我想我误解了你想要做什么。以上它不起作用,因为它的分类法不同,您需要预先保存您的永久链接并具有新分类法的模板。但我想我知道你想要什么,并且有一个简单的解决方案。我已经编辑了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2021-03-31
    • 1970-01-01
    • 2016-08-22
    • 2022-01-09
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    相关资源
    最近更新 更多