DaveyD DaveyD - 1 year ago 332
PHP Question

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.


Answer Source

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;
$myPdf = array_shift( wc_get_product_terms( $product->id, 'pa_pdfs', array( 'fields' => 'names' ) ) );

Reference: Woocommerce getting custom attributes