希望对某人来说是一个简单的修复!
我有一个自定义帖子类型,名为“产品”。
使用这段代码,我得到了每个“产品”的名称:
<?php
//Define your custom post type name in the arguments
$args = array('post_type' => 'products');
//Define the loop based on arguments
$loop = new WP_Query( $args );
//Display the contents
while ( $loop->have_posts() ) : $loop->the_post();
?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php endwhile;?>
这些产品中的每一个都在一个类别中。我想要做的是不仅获得 the_title,而且获得类别。
我尝试使用 <?php the_category(); ?>
但没有运气。
有人知道吗?
编辑:
抱歉,我在我的产品自定义帖子类型中创建了这些内容。
add_action( 'init', 'create_product_cat_external' );
function create_product_cat_external() {
register_taxonomy(
'ExternalProducts',
'products',
array(
'label' => __( 'External Products' ),
'rewrite' => array( 'slug' => 'externalproducts' ),
'hierarchical' => true,
)
);
}
add_action( 'init', 'create_product_cat_internal' );
function create_product_cat_internal() {
register_taxonomy(
'InternalProducts',
'products',
array(
'label' => __( 'Internal Products' ),
'rewrite' => array( 'slug' => 'internalproducts' ),
'hierarchical' => true,
)
);
}
它给我外部和内部产品作为类别。但在这些里面,我有在 wordpress 后端制作的类别。
这是我选择产品时的样子:
最佳答案
这有点困难,因为您将两种不同的分类法附加到您的帖子类型“产品”。由于您的分类法是分层的,因此将所有内容都放在一个分类法中,并将“内部产品”和“外部产品”放在顶层会更容易。在你的情况下,你将必须检查它们 - 我假设你的“产品”不能是“内部”和“外部” >'同时:
<?php
// Your query
$args = array('post_type' => 'products');
$loop = new WP_Query( $args );
// Your loop
while ( $loop->have_posts() ) : $loop->the_post();
?>
<h1 class="entry-title"><?php the_title(); ?></h1>
// Only print terms when the_terms is not false
<?php if (the_terms( $post->ID, 'InternalProducts') !== false) : ?>
<p><?php the_terms( $post->ID, 'InternalProducts', 'Category: Internal Products ', ' / ') ?></p>
<?php endif; ?>
<?php if (the_terms( $post->ID, 'ExternalProducts') !== false) : ?>
<p><?php the_terms( $post->ID, 'ExternalProducts', 'Category: External Products ', ' / ') ?></p>
<?php endif; ?>
<?php endwhile;?>
参见 WordPress Codex获取更多信息。
关于php - WordPress Taxonomy 获取类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29945015/