Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce - Get custom product attribute

I am trying to get a specific custom attribute in woocommerce. I've read tons of threads on this site which offer about 3-5 methods how to do it. After trying all, the only method that worked for me is to loop through all attributes - all others did not work. I have a custom attribute named 'pdfs'

The following tries did not work: (link)

 $global product;
 $myPdf = array_shift( wc_get_product_terms( $product->id, 'pdfs', array( 'fields' => 'names' ) ) );

 $myPdf = $product->get_attribute( 'pdfs' );

 $myPdf = get_post_meta($product->id, 'pdfs', true);

This is the only one that did work: (link)

 $attributes = $product->get_attributes();
 foreach ( $attributes as $attribute ) {
    if (attribute_label( $attribute[ 'name' ] ) == "pdfs" ) {
        echo array_shift( wc_get_product_terms( $product->id,  $attribute[ 'name' ] ) );
    }
}

I would much rather be able to use one of the first options Any help would be appreciated.
Thanks

like image 303
DaveyD Avatar asked Jul 20 '16 17:07

DaveyD


People also ask

How do I get the attribute of a product in WooCommerce?

Code to Display The Attributes$product = wc_get_product(42) $customsattributes = $product->get_attribute( 'customcharacters' ); $globalattributes = $product->get_attribute( 'pa_characters' ); echo "customcharacters value " . $customsattributes . ""; echo "pa_characters value " .

What are custom product attributes WooCommerce?

The purpose of a custom product attribute is the same – it is used to represent a certain feature of a product. However, unlike global product attributes, a custom attribute is used to define a feature of a specific product; it is not applicable to most other products.

How do I add a custom product attribute?

Go to: Products > Add Product (or edit an existing one). Select the Attributes tab in the Product Data. There you can choose any of the attributes that you've created in the dropdown menu. Select Add.


1 Answers

Update: Added compatibility for Woocommerce 3+

As attributes are always prepend with pa_ in DB, for getting them with wc_get_product_terms() function, you will need to use pa_pdfs instead of pdfs, this way:

global $product;

$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // Added WC 3+ support

$myPdf = array_shift( wc_get_product_terms( $product_id, 'pa_pdfs', array( 'fields' => 'names' ) ) );

Reference: How to get a products custom attributes from WooCommerce

like image 70
LoicTheAztec Avatar answered Oct 18 '22 02:10

LoicTheAztec