WooCommerce - Get Custom Product Attribute

I am trying to get a custom custom attribute in woocommerce. I read tons of threads on this site that offer about 3-5 methods for how to do this. After trying everything, the only method that worked for me was to iterate over all the attributes - all the others did not work. I have a custom attribute called "pdfs"

The following attempts did not help: ( 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 thing that works: ( 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 rather use one of the first options. Any help would be appreciated. Thanks

+4
source share
1 answer

Update: Added compatibility for Woocommerce 3+

pa_ is always added as attributes to the database, to get them using the wc_get_product_terms() function, you will need to use pa_pdfs instead of pdfs , thus:

 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' ) ) ); 

Link: How to get custom product attributes from WooCommerce

+7
source

All Articles