我需要创建一个允许我通过短代码显示分类的函数。
我试试这个但不起作用:
function category_in_content($atts){
global $post;
return get_the_terms( $post, 'course_category' );
}
add_shortcode( 'catcorso', 'category_in_content' );
分类名称是“course_category”。
答案 0 :(得分:0)
默认情况下add_shortcode返回html。 您可以尝试以下代码:
add_shortcode( 'catcorso', 'category_in_content' );
function category_in_content($atts){
global $post;
$html = '';
$taxonomy = 'course_category';
$terms = get_the_terms( $post, $taxonomy );
if ( !empty( $terms ) ) {
foreach ($terms as $term) {
$html .= '<a href="' . get_term_link( $term, $taxonomy ) . '">' . $term->name . '</a>';
}
}
return $html;
}
答案 1 :(得分:0)
用这个解决了:
function cat_title(){
global $post;
$categories = get_the_terms( $post, 'course_category' );
if ( isset( $categories[0] ) ) {
return '<a href="' . esc_url( get_term_link( $categories[0] ) ) . '" title="' . esc_attr( $categories[0]->name ) . '">' . esc_html( $categories[0]->name ) . '</a>';
}
}
add_shortcode( 'catcorso', 'cat_title' );