我有一个与相关职位的职位。我与高级自定义字段插件建立关系。我可以显示该术语的所有相关帖子,但除此之外,我只想显示该术语的名称作为标题。这行不通
//get Assistance
$post = $post_objects; // variable must be called $post (IMPORTANT)
setup_postdata($post);
if(!empty(is_object_in_term($post->ID, \'tshowcase-taxonomy\',Assistence))) {
//if ($loop->have_posts()) {
echo \'<h4><i>\' . Assistence . \'</i></h4>\';
}else{
echo \'empty\';
}
//endforeach;
/* while($loop->have_posts()) : $loop->the_post();
echo \'<a href="\'.get_permalink().\'">\'.get_the_title().\'</a><br>\';
endwhile;*/
//wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
foreach ($post_objects as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post);
if (is_object_in_term($post->ID, \'tshowcase-taxonomy\', Assistence)) {
if (has_post_thumbnail()) {
echo \'<a href="\' . get_permalink() . \'">\' . get_the_title() . "<br>" . get_the_post_thumbnail($postid, array(150, 150), array()) . \'</a><br>\';
} else {
echo \'<a href="\' . get_permalink() . \'">\' . get_the_title() . \'</a><br>\';
}
}
endforeach;
echo \'<br>\';
/* while($loop->have_posts()) : $loop->the_post();
echo \'<a href="\'.get_permalink().\'">\'.get_the_title().\'</a><br>\';
endwhile;*/
wp_reset_postdata();
显示所有相关帖子的循环有效。但是上面的代码,如果没有与这个词相关的帖子,只显示标题也会显示标题。有人知道这个问题的解决方案吗?非常感谢!
最合适的回答,由SO网友:deflime 整理而成
考虑到您提供的代码,最简单的方法是颠倒代码的顺序。执行foreach
在标题之前,而不是使用echo
, 附加到变量。然后检查变量是否有任何输出,如果有,则输出标题。
$post = $post_objects;
setup_postdata($post);
# create variable collect content
$content = \'\';
foreach ($post_objects as $post):
setup_postdata($post);
if (is_object_in_term($post->ID, \'tshowcase-taxonomy\', Assistence)) {
if (has_post_thumbnail()) {
# append content to $content variable
$content .= \'<a href="\' . get_permalink() . \'">\' . get_the_title() . "<br>" . get_the_post_thumbnail($postid, array(150, 150), array()) . \'</a><br>\';
} else {
# append content to $content variable
$content .= \'<a href="\' . get_permalink() . \'">\' . get_the_title() . \'</a><br>\';
}
}
endforeach;
# check if $content variable has content
if( $content != \'\' ) {
echo \'<h4><i>\' . Assistence . \'</i></h4>\';
echo $content;
echo \'<br>\';
}else{
echo \'empty\';
}
wp_reset_postdata();