下面的代码为页面启用类别。提供了一个示例页面模板,该模板循环浏览分配给页面的类别,并显示每个类别的帖子。
如果要限制用户仅选择一个类别,可以使用以下解决方案:Taxonomy Single Term.
关联category
分类学page
岗位类型:
function wpse_page_category() {
register_taxonomy_for_object_type( \'category\', \'page\' );
}
add_action( \'init\', \'wpse_page_category\', 999 );
简单页面模板示例(template page categories.php):
<?php
/**
* Template Name: Page Categories
*
*/
get_header(); ?>
<?php
// Standard loop for page content
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
the_title( \'<h1>\', \'</h1>\' );
the_content();
}
}
// Get the category assigned to this page and list the posts in this category.
// This code works when multiple categories have been assigned to the page.
$page_categories = get_the_terms( get_the_ID(), \'category\' );
if ( $page_categories && ! is_wp_error( $page_categories ) ) {
foreach ( $page_categories as $page_category ) {
$posts_query = new WP_Query( [
\'post_type\' => \'post\',
\'cat\' => $page_category->term_id,
] );
if ( $posts_query->have_posts() ) {
echo \'<h2> Posts from the <em>\' . esc_html( $page_category->name ) . \'</em> category:</h2>\';
while ( $posts_query->have_posts() ) {
$posts_query->the_post();
the_title( \'<h3>\', \'</h3>\' );
//the_content();
}
echo \'<hr>\';
}
}
}
?>