我已经为我的帖子创建了一个名为“Regions”的自定义分类法我已经用这些区域标记了2个帖子。我想做的是列出任何带有区域标记的帖子,但由于某些原因,它不起作用。下面是我注册自定义分类法的函数:
function region_taxonomy() {
$labels = array(
\'name\' => _x( \'Regions\', \'taxonomy general name\' ),
\'singular_name\' => _x( \'Region\', \'taxonomy singular name\' ),
\'search_items\' => __( \'Search Regions\' ),
\'all_items\' => __( \'All Regions\' ),
\'parent_item\' => __( \'Parent Region\' ),
\'parent_item_colon\' => __( \'Parent Region:\' ),
\'edit_item\' => __( \'Edit Region\' ),
\'update_item\' => __( \'Update Region\' ),
\'add_new_item\' => __( \'Add New Region\' ),
\'new_item_name\' => __( \'New Region Name\' ),
\'menu_name\' => __( \'Regions\' )
);
register_taxonomy(\'regions\',array(\'post\'), array(
\'hierarchical\' => true,
\'labels\' => $labels,
\'show_ui\' => true,
\'show_admin_column\' => true,
\'query_var\' => true,
\'rewrite\' => array( \'slug\' => \'region\' )
));
}
add_action(\'init\', \'region_taxonomy\', 0);
下面是
WP_Query
从我的页面模板:
<?php
$args = array(
\'orderby\' => \'date\',
\'post_type\' => \'post\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'regions\'
),
),
\'posts_per_page\' => \'-1\'
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
不幸的是,这是返回没有帖子,即使我有2个帖子标记了一个地区。有什么想法吗?
最合适的回答,由SO网友:obiPlabon 整理而成
没有terms
参数因此,您必须首先查询所有regions 然后将术语ID分配给分类查询。
以下是解决方案-
$terms = get_terms( array(
\'taxonomy\' => \'regions\',
\'fields\' => \'id=>slug\',
) );
$args = array(
\'orderby\' => \'date\',
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'tax_query\' => array(
array(
\'taxonomy\' => \'regions\',
\'field\' => \'term_id\',
\'terms\' => array_keys( $terms ),
),
),
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_content();
}
wp_reset_postdata();
} else {
echo \'<p>Sorry, there are no posts to display</p>\';
}
顺便说一句,你不应该使用
wp_reset_query()
它很昂贵,应该与
query_posts()
只能改用
wp_reset_postdata()
.