5

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

Community
  • 1
  • 1
DaveyD
  • 337
  • 1
  • 5
  • 15

1 Answers1

8

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • I'm get --> Notice: Only variables should be passed by reference. Woocommerce version 3.2.6. Code ---> $date = array_shift( wc_get_product_terms( $product->get_id(), 'pa_date', array( 'fields' => 'names' ) ) ); What can be wrong? I can't solve it. I get 'Null' of gettype($date). Maybe I could get some help? – Kristis Feb 17 '18 at 18:55
  • @Kristis Updated the answer Adding WC 3+ compatibility… try it again. – LoicTheAztec Feb 17 '18 at 22:54
  • Thanks, but I get same notice and type 'Null'. Just in case this is my full code http://collabedit.com/vejqr – Kristis Feb 18 '18 at 02:12
  • @Kristis You should better ask a new complete and detailed question on StackOverFlow, as your case is something different. – LoicTheAztec Feb 18 '18 at 02:33