首先我要说的是我没有 php 背景。
我需要嵌入一个短代码来显示与帖子关联的特定分类的名称。
短代码嵌入在食谱单帖子模板中。
我找到了一个似乎接近我正在寻找的答案。 此页面的答案: 在标题中显示分类术语而不是类别
解决方案中显示的代码是:
// Get taxonomy terms specifc to current post
$terms = get_the_terms( $post->ID , 'your-taxonomy-name-here' );
foreach ( $terms as $term ) {
echo ' <a href="' .esc_url( home_url( '/' ) ). $term->slug . '" title="' . $term->name . '" ' . '>' . $term->name .'</a> ';
}
根据这段代码我尝试了以下代码,没有成功:
备注:
非常感谢您的帮助
请尝试以下代码来获取与帖子相关的所有分类法。
确保您收到正确的帖子 ID 和正确的分类名称,因此您可能需要一些调试,如果您遇到任何问题,请告诉我。我很乐意提供进一步帮助。
function display_post_taxonomy_terms( $atts ) {
// Get post ID
$post_id = get_the_ID();
// Check if post ID exists
if ( $post_id ) {
// Get taxonomy terms associated with the post
$terms = get_the_terms( $post_id, 'your_taxonomy_name' ); // Replace 'your_taxonomy_name' with the name of your taxonomy
// Check if terms exist
if ( $terms && ! is_wp_error( $terms ) ) {
$taxonomy_list = '<ul>';
foreach ( $terms as $term ) {
$taxonomy_list .= '<li><a href="' . esc_url( get_term_link( $term ) ) . '">' . esc_html( $term->name ) . '</a></li>';
}
$taxonomy_list .= '</ul>';
return $taxonomy_list;
}
}
return ''; // Return empty string if no taxonomy terms found
}
add_shortcode( 'display_post_taxonomy', 'display_post_taxonomy_terms' );