简体   繁体   中英

Get only post terms for Woocommerce product tags?

My function outputs all used Woocommerce product tags, on every product.

How can I sort out/output only tags that every single product has selected from backend?

Here is my code:

add_action( 'woocommerce_before_shop_loop_item', 'woocommerce_product_loop_tags', 5 );
add_action( 'woocommerce_product_thumbnails', 'woocommerce_product_loop_tags',  5 );

function woocommerce_product_loop_tags() {
    global $post, $product;
        if ( is_array (get_terms( 'product_tag' ))) {
           $tags = get_terms( 'product_tag' , 'orderby=id' );
           echo '<span class="badge-cloud">';
           foreach($tags as $tag) {
              echo '<span rel="tag" class="fl-badge '.$tag->slug.'"><p>'.$tag->name.'</p></span>';
           } 
           echo '</span>';
        } 
}

The correct way is o use wp_get_post_terms() where you can set the post ID for a given taxonomy to get the terms for this specific post ID. So your code should be:

add_action( 'woocommerce_before_shop_loop_item', 'woocommerce_product_loop_tags', 5 );
add_action( 'woocommerce_product_thumbnails', 'woocommerce_product_loop_tags',  5 );
function woocommerce_product_loop_tags() {
    global $post;

    $taxonomy = 'product_tag';
    $args = 'orderby=id';
    $product_tags = wp_get_post_terms( $post->ID, $taxonomy, $args );

    if ( count($product_tags) > 0 ){
        echo '<span class="badge-cloud">';
        foreach( $product_tags as $term )
            echo '<span rel="tag" class="fl-badge '.$term->slug.'"><p>'.$term->name.'</p></span>';
        echo '</span>';
    }
}

Code goes in function.php file of your active child theme (active theme or in any plugin file).

Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM