首页 > 解决方案 > Wordpress通过循环获取术语当前类别问题

问题描述

我无法正确显示循环类别。只需要在点亮的帖子中显示一个类别。为什么第一个帖子获得所有选定的类别,而下一个帖子已经正确显示了一个类别。如何仅在第一篇文章中显示当前选择的类别?我的代码看起来像这样。我附上了图片。

我的循环自定义帖子

<?php
/* Start the Loop */
$args = array( 'post_type' => 'database',
               'posts_per_page' => 10,
               'paged' => $paged,
               'post_status' => 'publish',
               'ignore_sticky_posts' => true,
               'order' => 'DESC', 
               'orderby' => 'date');

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();

这是为了在循环帖子中显示一个类别

<?php   
// Get terms for post
$terms = wp_get_post_terms( $post->ID , 'database_categories' ,$args2);
$args2 = array( 'parent' => 39,
                'fields' => 'all');

// Loop over each item since it's an array
if ( $terms != null ) {
    foreach( $terms as $term ) {
        $term_link = get_term_link( $term, 'database_categories' );
        // Print the name and URL
        echo '<a href="' . $term_link . '">' . $term->name . '</a> ';
// Get rid of the other data stored in the object, since it's not needed
unset($term); 
    } 
} 
?>      

我的循环图像

标签: phpwordpresstaxonomy-terms

解决方案


如果这里的目标是获取第一个术语并忽略其余部分,那么我只需移开第一个数组元素,不需要在术语上进行循环。

$args2 = array('parent' => 39, 'fields' => 'all');
$terms = wp_get_post_terms( $post->ID , 'database_categories' ,$args2);

if (!empty($terms)) {
    $term = array_shift($terms);
    echo sprintf('<a href="%s">%s</a>', get_term_link( $term, 'database_categories' ), $term->name);
}

推荐阅读