我注册了一个自定义的帖子类型"Projects",还为该帖子类型注册了一种名为"Project Categories"的自定义分类法。在我的主页上,我有一个div,我想在其中列出"项目类别"分类法中的所有项目和术语。目前,我只能获得条款列表。有人能告诉我为什么我无法显示这些条款吗。目前,我有:
<div class="list-container">
<?php
query_posts( array( 'post_type' => 'projects' ) );
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; wp_reset_query(); ?>
<?php $taxonomy = 'project_categories';
$tax_terms = get_terms($taxonomy);
?>
<?php foreach ($tax_terms as $cat): ?>
<li><?php $cat; ?></li>
<?php endforeach; ?>
</div><!--end list-container-->
我的另一个问题是,在query_posts循环内部还是外部包含分类法更好?
get_terms($taxonomy)
返回一个对象数组(请参阅WP Codex中的get_terms()),因此为了打印名称,您应该使用<?php echo $cat->name ?>
(不要忘记echo)。
我试图更正你的代码。有关详细信息,请参阅代码块中的注释:
<?php
// keep your queries outside the loop for more readable code
query_posts( array( 'post_type' => 'projects' ) );
$taxonomy = 'project_categories';
$tax_terms = get_terms($taxonomy);
?>
<!-- <li> should be enclosed in <ul> or <ol> -->
<ul class="list-container">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li><a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
<?php foreach ($tax_terms as $cat): ?>
<li><?php echo $cat->name; ?></li>
<?php endforeach; ?>
</ul><!--end list-container-->
<?php wp_reset_query(); ?>
旁注:使用<?php the_permalink(); ?>
或<a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a>
。前者将自动完成所有魔法,在这种情况下推荐使用。