I wrote a lightweight plugin to produce a list of all the terms in a custom taxonomy, which works perfectly. I would like to modify this to produce a list of all the terms for a particular post but I’m struggling with the right way to get_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
) );
Full code is as follows (with suggested mods), it’s currently generating a ‘there has been a critical error on this website’ message
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' => '',
'name' => 'category',
'hide_empty' => false,
'exclude' => '',
'include' => '',
'order' => 'ASC',
), $atts);
global $post;
$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
) );
$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;
}
2
Answers
Passing the id attribute in the shortcode will do this.