我使用这段代码首先将每个类别术语显示为标题,然后显示一篇文章,该文章分配给标题下的每个类别术语。
如果我创建自定义分类法,它会按预期工作,但如果我尝试使用默认类别分类法,标题会按预期显示,但在每个标题下,它会显示每篇文章,而不考虑指定的术语。我不明白为什么它适用于我的自定义分类法,但不适用于默认类别分类法。
<?php $args = array (
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'hide_empty\' => true,
);
$terms = get_terms( \'category\', $args );
foreach ( $terms as $term ) {
echo $term->name;
$post_args = array (
\'category\' => $term->name,
\'posts_per_page\' => \'1\',
\'no_found_rows\' => true
);
$query = new WP_Query( $post_args );
while ( $query->have_posts() ) {
$query->the_post(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php }
}
如果在本例中我将其更改为使用名为“article\\u subjects”的自定义分类法,则一切都会正常工作。
<?php $args = array (
\'orderby\' => \'name\',
\'order\' => \'ASC\',
\'hide_empty\' => true,
);
$terms = get_terms( \'article_subjects\', $args );
foreach ( $terms as $term ) {
echo $term->name;
$post_args = array (
\'article_subjects\' => $term->name,
\'posts_per_page\' => \'1\',
\'no_found_rows\' => true
);
$query = new WP_Query( $post_args );
while ( $query->have_posts() ) {
$query->the_post(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php }
}
为了以防万一,这是我用来生成自定义分类法的代码。
function article_subjects() {
$labels = array(
\'name\' => _x( \'Subjects\', \'Taxonomy General Name\', \'dc\' ),
\'singular_name\' => _x( \'Subject\', \'Taxonomy Singular Name\', \'dc\' ),
\'menu_name\' => __( \'Subjects\', \'dc\' ),
\'all_items\' => __( \'All Items\', \'dc\' ),
\'parent_item\' => __( \'Parent Item\', \'dc\' ),
\'parent_item_colon\' => __( \'Parent Item:\', \'dc\' ),
\'new_item_name\' => __( \'New Subject\', \'dc\' ),
\'add_new_item\' => __( \'Add New Item\', \'dc\' ),
\'edit_item\' => __( \'Edit Item\', \'dc\' ),
\'update_item\' => __( \'Update Item\', \'dc\' ),
\'separate_items_with_commas\' => __( \'Separate items with commas\', \'dc\' ),
\'search_items\' => __( \'Search Items\', \'dc\' ),
\'add_or_remove_items\' => __( \'Add or remove items\', \'dc\' ),
\'choose_from_most_used\' => __( \'Choose from the most used items\', \'dc\' ),
\'not_found\' => __( \'Not Found\', \'dc\' ),
);
$args = array(
\'labels\' => $labels,
\'hierarchical\' => false,
\'public\' => true,
\'show_ui\' => true,
\'show_admin_column\' => true,
\'show_in_nav_menus\' => true,
\'show_tagcloud\' => true,
\'has_archive\' => true,
\'can_export\' => true
);
register_taxonomy( \'article_subjects\', array( \'post\' ), $args );
}
add_action( \'init\', \'article_subjects\', 0 );