问题描述
我编写了一个轻量级插件来生成自定义分类法中所有术语的列表,效果很好。我想修改它以生成特定帖子的所有条款列表,但我正在努力寻找正确的方法来获取_the_terms
function antls_taxonomy_list( $atts ) {
$atts = shortcode_atts( array(
'post_id' => '','name' => 'category','hide_empty' => false,'exclude' => '','include' => '','order' => 'ASC',),$atts);
$terms = get_the_terms( array(
'post_id' => '','taxonomy' => $atts['name'],'hide_empty' => $atts['hide_empty'],'orderby' => 'name','order' => $atts['order'],'parent' => 0
) );
完整代码如下(带有建议的模组),目前正在生成“此网站出现严重错误”消息
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define('ANTLS_PLUGIN_DIR_URL',plugin_dir_url( __FILE__ ) );
add_shortcode( 'tax_taxonomy_list','antls_taxonomy_list' );
function antls_taxonomy_list( $atts ) {
$atts = shortcode_atts( array(
'post_id' => '',$atts);
global $post;
$terms = get_the_terms( array(
'post_id' => $post->ID,//ID from the $post object
'taxonomy' => $atts['name'],'parent' => 0
) );
$html .= '<ul class="antls tax-list-'.$atts['name'].'">';
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
if( !empty( $atts['exclude'] ) ) {
$exclude = explode( ',',$atts['exclude'] );
if( in_array( $term->term_id,$exclude) ) {
continue;
}
}
if( !empty( $atts['include'] ) ) {
$include = explode( ',$atts['include'] );
if( !in_array( $term->term_id,$include) ) {
continue;
}
}
$html .= '<li class="tax-item-'.$atts['name'].'" data-taxname="'.strtolower( $term->name ).'">';
$term_link = get_term_link( $term );
$html .= '<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>';
$html .= '</li>';
}
}
$html .= '</ul>';
return $html;
}
解决方法
在短代码中传递 id 属性会做到这一点。
//Static
[shortcode id="123"]
//Dynamic. Get the ID of the current post
global $post; //Declare global post variable
$terms = get_the_terms( array(
'post_id' => $post->ID,//ID from the $post object
'taxonomy' => $atts['name'],'hide_empty' => $atts['hide_empty'],'orderby' => 'name','order' => $atts['order'],'parent' => 0
) );