Home WordPressWooCommerce How to Get attributes of product from product ID ?

How to Get attributes of product from product ID ?

by admin
0 comment 119 views

How to Get attributes of product from product ID ?

Following code gives the attributes of a product from product ID, This is done by calling global $product.

To get the attributes added in product a function $product->get_attributes( ); gives the array of attributes.

Rest of the following Code is given Below to get all values from array.

function labotrees_shop_attributes()
{
    global $product;

    //Getting product attributes
    $product_attributes = $product->get_attributes();

    if(!empty($product_attributes))
    {
      //Getting product attributes slugs
      $product_attribute_slugs = array_keys($product_attributes);
      $count_slug = 0;

       foreach ($product_attribute_slugs as $product_attribute_slug)
       {
         $count_slug++;
         // Removing "pa_" from attribute slug and adding a cap to first letter
         $attribute_name =  ucfirst( str_replace('pa_', '', $product_attribute_slug) );
         echo '<li><strong>'. $attribute_name. '</strong> ';

         ##  ===>  ===>  // Getting the product attribute values
         $attribute_values = get_terms($product_attribute_slug);
         $count_value = 0;
         foreach($attribute_values as $attribute_value)
         {
           $count_value++;
           $attribute_name_value = $attribute_value->name; // name value
           $attribute_slug_value = $attribute_value->slug; // slug value
           $attribute_slug_value = $attribute_value->term_id; // ID value

           // Displaying HERE the "names" values for an attribute
           echo $attribute_name_value;
           if($count_value != count($attribute_values)) echo '</li> ';
        }

    }

   }
}

At last Short code is used to show the values on a page.

add_shortcode('show_product_attributes', 'labotrees_shop_attributes');

Leave a Comment

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy