php - 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);
}
}
?>
解决方案
如果这里的目标是获取第一个术语并忽略其余部分,那么我只需移开第一个数组元素,不需要在术语上进行循环。
$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);
}
推荐阅读
- python - 如何在 TensorFlow 图中编写 if 语句?
- c++ - 基于现有随机访问迭代器的 C++ 反向迭代器?
- android - 在 Android 中保存位图后,图像未显示在图库中
- javascript - 如何访问我的数据并将其转换为表格格式
- scala - 从现有数据框创建新列
- wordpress - Wordpress enqueue_script 在平板电脑上不起作用
- linux - 此计算机未启用 VT-X/AMD-v
- java - 错误信息“com.mysql.cj.exceptions.WrongArgumentException:数据库 URL 不能为空”是什么意思。意思是?
- reactjs - 在其中设置状态时去抖动不起作用
- r - 使用单个代码读取多个 .csv 文件