Display Most Popular Product Tags in WooCommerce s

2019-08-04 06:22发布

问题:

I found this code (http://devotepress.com/faqs/display-popular-tags-wordpress) and I used the short code ([wpb_popular_tags]) but I do not see any result.

How can I use this code for displaying most popular WooCommerce product tags?

Here is their code:

function wpb_tag_cloud() {
    $tags = get_tags();
    $args = array(
        'smallest' => 10,
        'largest' => 22,
        'unit' => 'px',
        'number' => 10,
        'format' => 'flat',
        'separator' => " ",
        'orderby' => 'count',
        'order' => 'DESC',
        'show_count' => 1,
        'echo' => false
    );

    $tag_string = wp_generate_tag_cloud( $tags, $args );

    return $tag_string;
}

// Add a shortcode so that we can use it in widgets, posts, and pages
add_shortcode('wpb_popular_tags', 'wpb_tag_cloud');

// Enable shortcode execution in text widget
add_filter ('widget_text', 'do_shortcode'); 

回答1:

First, what do you have to know that you don't know may be:
Classic WordPress post tags are very different than WooCommerce "Product tags" which have a different custom taxonomy 'product_tag'.

So you cant use WordPress get_tags() to get the product tags.

Instead you should replace it with get_terms( 'product_tag' ) this way:

function wpb_tag_cloud() {
    $tags = get_terms( 'product_tag' );
    $args = array(
        'smallest' => 10,
        'largest' => 22,
        'unit' => 'px',
        'number' => 10,
        'format' => 'flat',
        'separator' => " ",
        'orderby' => 'count',
        'order' => 'DESC',
        'show_count' => 1,
        'echo' => false
    );
    $tag_string = wp_generate_tag_cloud( $tags, $args );
    return $tag_string;
}

// Add a shortcode so that we can use it in widgets, posts, and pages
add_shortcode('wpb_popular_tags', 'wpb_tag_cloud');

// Enable shortcode execution in text widget
add_filter ('widget_text', 'do_shortcode'); 

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

USAGE - You will need to:

  1. Add the "text" widget in your woocommerce widget bar area.
  2. Add in the editor of this "text" widget the short code [wpb_popular_tags] (then save)

This time you will get All your "most popular" product tags *(The ones that you have set and enabled for your product)*s.

Tested in WooCommerce 3+ and perfectly works.