![](/img/trans.png)
[英]Adding class “current_page_item” for custom post type category list(note: the category is belong in custom taxonomy)
[英]Custom Post Type displays post belong on the category
我有一个自定义帖子类型advice
和分类法adcat
。 我想显示属于该类别的所有帖子。
可以说我有4个类别,即“游戏”,“旅游”,“菜肴”,“酒店”,这4个类别也是菜单。 例如,如果我单击类别之一:所有显示酒店的帖子都应显示。
顺便说一下,我曾经用这段代码来显示wordpress默认类别:
<?php $catname = wp_title('', false); ?>
<?php $posts = get_posts("category_name=$catname&numberposts=8&offset=0");
foreach ($posts as $post) : start_wp(); ?>
//html output
<h1><?php the_title(); ?></h1>
<?php endforeach; ?>
这不适用于自定义帖子“分类法”,任何建议都会有所帮助,谢谢
尝试这样的事情,这是按类别ID获取帖子的示例
$args = array( 'cat' => $cat_id, 'post_type' => 'advice', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
endwhile;
wp_reset_postdata();
您也可以使用类别名称。
$args = array('category_name' => 'catname', 'post_type' => 'advice', 'posts_per_page' => -1 );
您可以根据需要使用post_per_page,我为所有帖子添加了-1
我不太了解您的用语。 在谈论adcat
,它是自定义分类法还是内置分类法category
的术语。 如果adcat
是自定义分类法,则应在tax_query
中使用WP_Query
,而不是类别参数。
请记住,类别和自定义分类法都是分类法,其直接子级称为术语,而其直接子级称为子术语
您也不应使用wp_title()
获取查询对象。 您应该使用get_query_var()
来获取查询的对象。 对于类别将是cat
,分类将taxonomy
和术语term
。 看看get_categories
, get_taxonomies
和get_terms
的返回值
例
$category = get_query_var( `cat` );
$cat_slug = $category->slug;
现在,您可以将$cat_slug
作为category_name
返回到自定义查询
编辑
我很快重新考虑了整个过程,并检查了您的评论。 为什么不直接复制index.php并将其重命名为taxonomy.php。 此处完全不需要自定义查询。 taxonomy.php中的默认循环应该做到这一点
编辑2
要进一步阅读,请查看以下文章
不确定我是否正确阅读了您的答案,但是我假设您是要按照正确的分类学术语搜索帖子? 因此,在adcat
分类中,您将“游戏”,“旅游”,“菜”,“酒店”作为您的术语或类别。 最好的选择是在查询参数中使用tax_query
。 这是使用WP_Query()对象执行此操作的方法。
<?php
$args = array(
'post_type' => 'advice',
'posts_per_page' => 8,
'tax_query' => array(
'taxonomy' => 'adcat',
'terms' => array('games', 'tours', 'dishes', 'hotels'),
'field' => 'slug'
)
);
$query = new WP_Query($args);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
重要说明:使用WP_Query时,您将覆盖默认的帖子数据。 因此,为了取回该数据,您只需使用wp_reset_postdata()
如循环结束后在上例中所见。
试试这个也许行得通...我写了一条便条,这样您就可以看到发生了什么..希望对您有所帮助
<?php
// Get the term/category of the post
$terms = get_the_terms( $post->ID , 'advice-cat' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'advice cat' );
}
//WordPress loop for custom post type
$terms = get_the_terms( $post->ID , 'advice-cat' );
$my_query = new WP_Query('post_type=advice&advice-cat=' . $term->name . '&posts_per_page=-1');
while ($my_query->have_posts()) : $my_query->the_post(); ?>
// output content
<?php the_title(); ?>
<?php endwhile; wp_reset_query(); ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.