簡體   English   中英

如何只為頁面添加類別?

[英]How to add categories for pages only?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM