php - 如何仅为页面添加类别?
问题描述
我在我的 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');
推荐阅读
- sql - Repeat the Column values for the key multiple times in SQL SAP hana
- javascript - 如何以角度循环数组数组?请展示一些方法
- sql - How can I replace multiple words of a string in SQL
- sql - 我们如何将 VarChar 输入传递给 SQL 函数?
- django - PostgreSQL:如何从 Azure 数据湖 (ADLS) 存储和获取历史 SQL 数据
- emacs - 从浏览器即时复制文本并立即将列表发送到组织文档?
- html - 如何为标题添加边框?
- azure-devops - Azure DevOps 编辑默认主题分支名称
- javascript - 我如何将 Django 与 html CSS JS 一起使用?
- python - 生成以下字符串的格式 - 随机顺序