我想制作两个短代码来显示 Woocommerce 产品。
简码1:
简码2:
我尝试过这个短代码,但显示的标签不是链接。 我希望将它们显示为链接。
add_shortcode( 'wc_product_tag', 'get_tag_term_name_for_product_id' );
function get_tag_term_name_for_product_id( $atts ) {
// Shortcode attribute (or argument)
extract( shortcode_atts( array(
'taxonomy' => 'product_tag', // The WooCommerce "product tag" taxonomy (as default)
'product_id' => get_the_id(), // The current product Id (as default)
), $atts, 'wc_product_tag' ) );
$term_names = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
if( ! empty($term_names) ){
// return a term name or multiple term names (in a coma separated string)
return implode(', ', $term_names);
}
}
您可以使用以下简码来获取链接术语:
add_shortcode( 'wc_product_cat', 'get_linked_term_names_for_product' );
function get_linked_term_names_for_product( $atts ) {
// Shortcode attribute (or argument)
extract( shortcode_atts( array(
'taxonomy' => 'product_cat', // Product categories as default (Use 'product_tag' for product tags)
'product_id' => get_the_id(), // current default product Iddefault)
), $atts, 'wc_product_cat' ) );
$terms = (array) wp_get_post_terms( $product_id, $taxonomy );
$linked_terms = array(); // Initializing
if( empty($terms) ) return; // Exit
// Loop through each term
foreach ( $terms as $term ) {
$term_link = get_term_link($term); // get term link
$linked_terms[] = $term_link ? sprintf( '<a href="%s">%s</a>', $term_link, $term->name ) : $term->name;
}
return implode(', ', $linked_terms);
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
使用
[wc_product_cat]
[wc_product_cat taxonomy="product_tag"]