4

I want to display some specific product attributes of my choice on the store shop page for each product. It is necessary to display the name of the attribute and opposite its value. I started writing code, I wanted to print at least names, but I only show the name of the last attribute

add_action('woocommerce_after_shop_loop_item','add_attribute');
function add_attribute() {
    global $product;
    $weigth_val = $product->get_attribute('weight');
    $quant_val = $product->get_attribute('quantity');
    $length_val = $product->get_attribute('length');
    echo $weigth_val;
    echo $quant_val;
    echo $length_val;
}
LoicTheAztec
  • 184,753
  • 20
  • 224
  • 275
Aleks Pvn
  • 131
  • 1
  • 2
  • 10

1 Answers1

9

In woocommerce each product attribute is a custom taxonomy and are recorded in database adding pa_ to the beginning of their slugs…

That taxonomy name is to be used with WC_Product get_attribute() method.

So so your code should be instead:

add_action('woocommerce_after_shop_loop_item','displaying_product_attributes');
function displaying_product_attributes() {
    global $product;

    $weigth_val = $product->get_attribute('pa_weight');
    $quant_val  = $product->get_attribute('pa_quantity');
    $length_val = $product->get_attribute('pa_length');

    echo $weigth_val;
    echo $quant_val;
    echo $length_val;
}

It should work now…


To get the product attribute name label and with the corresponding name value for products you will use:

add_action('woocommerce_after_shop_loop_item','add_attribute');
function add_attribute() {
    global $product;

    $product_attributes = array( 'pa_weight', 'pa_quantity', 'pa_length', 'pa_color' );
    $attr_output = array();

    // Loop through the array of product attributes
    foreach( $product_attributes as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
            $value = $product->get_attribute('pa_weight');

            if( ! empty($value) ){
                // Storing attributes for output
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
            }
        }
    }

    // Output attribute name / value pairs separate by a "<br>"
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output ).'</div>';
}

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

LoicTheAztec
  • 184,753
  • 20
  • 224
  • 275
  • Sorry, for my deleted comment above, this worked. Tell me, please, how do I output these values, also the attribute names – Aleks Pvn Apr 03 '18 at 12:50
  • I'm trying to do something similar but I want to add a column in the WooCommerce Products grid, there is only one attribute to lookup, no label needed, I need to lookup possible attribute values for each product, is it possible? – Ritardi.Net Nov 22 '18 at 11:42