我有一段有用的代码,可以创建一个短代码,并在帖子上显示帖子标记及其描述。我试图显示分配给特定实时帖子的所有标签,而不是站点的所有标签等。
如果我使用echo
术语/描述最终显示在内容的顶部,而不是显示在短代码所在的元素中;如果我使用return
仅显示第一个标记,而忽略其他标记。
如能找到解决方案,将不胜感激。谢谢
function returnpost_tags() {
return get_the_tag_list( \'\', \', \', \'\' );
}
add_shortcode( \'post-tags\', \'returnpost_tags\' );
function returnpost_tagsdesc() {
// get tags by post ID
$post_ID = get_the_ID();
// here, you can add any custom tag
$terms = get_the_terms( $post_ID , \'post_tag\', array( "description" => "ids" ) );
foreach ( $terms as $term ) {
// The $term is an object, so we don\'t need to specify the $taxonomy.
$term_link = get_term_link( $term );
$term_ID = $term->term_id;
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
//echo \'\' . $term->name . \'\';
return term_description($term_ID);
// another option
// echo \'<p>\' . $term->description . \'</p>\';
}
}
add_shortcode( \'post-tags-desc\', \'returnpost_tagsdesc\' );
最合适的回答,由SO网友:Johansson 整理而成
您需要将每个标记存储在一个变量中,然后返回整个内容。在foreach
并将数据附加到其中。不要使用return
在循环内部,因为一旦到达第一个return
. 看看我修改过的这段代码:
// Define an empty variable
$data = \'\';
foreach ( $terms as $term ) {
// The $term is an object, so we don\'t need to specify the $taxonomy.
$term_link = get_term_link( $term );
$term_ID = $term->term_id;
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
// Append each term\'s description to it
$data .= term_description($term_ID);
}
// Return the entire data
return $data;