Display Variable Product Attributes and Terms on Woocommerce Archives

后端 未结 1 1224
悲哀的现实
悲哀的现实 2021-01-21 10:53

I am trying to accomplish a attribute and term list on the shop page using the hook woocommerce_shop_loop_item_title. The goal is to get the attribute(s) and term(s

1条回答
  •  星月不相逢
    2021-01-21 11:18

    Uppdate 2020 - Removed an error when trying to get the term name from a term slug.

    In your first code snippet there are some mistakes:

    • the $product variable was not defined
    • The function needed to be restricted to variable products only
    • the $attributes_and_terms_names variable was not initialized…

    Here is the revisited code (without the spaces between the rows):

    add_action( 'woocommerce_shop_loop_item_title', 'variable_att_and_terms_on_loop');
    function variable_att_and_terms_on_loop() {
        global $product;
    
        if( ! $product->is_type('variable') ) return; // Only for variable products
    
        $variation_attributes = $product->get_variation_attributes();
    
        if( sizeof($variation_attributes ) == 0 ) return; // Exit if empty
    
        $attributes = array(); // Initializing
    
        foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ) {
            $taxonomy_label = wc_attribute_label( $taxonomy, $product );
    
            $terms_name = array();
    
            foreach($terms_slug as $term_slug ) {
                // We try to get the term name when it's a term slug
                $term         = get_term_by('slug', $term_slug, $taxonomy);
                $terms_name[] = ! is_a($term, 'WP_Term') ? $term_slug : $term->name; 
            }
            $attributes[] = $taxonomy_label . ': ' . implode( ', ', $terms_name );
        }
    
        echo '
    '; echo '' . implode('
    ', $attributes) . ''; echo '
    '; }

    Code goes in function.php file of your active child theme (active theme). Tested and works.

    0 讨论(0)
提交回复
热议问题