6

I want to get the ID of a Woocommerce product attribute using the attribute name. e.g. pa_foobar

I know that product attributes are taxonomies, but get_taxonomy() doesn't return the taxonomy ID. I can't find a Woocommerce function that does this.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Robbie Lewis
  • 2,844
  • 3
  • 18
  • 29
  • This has already been answered in [this answer thread](https://stackoverflow.com/questions/47518333/create-programmatically-a-variable-product-and-two-new-attributes-in-woocommerce/47844054#47844054) – LoicTheAztec Apr 29 '18 at 19:41
  • 2
    @LoicTheAztec not true, you can't find best solution there (to use `wc_attribute_taxonomy_id_by_name('pa_foobar')`). – Artur Czyżewski Apr 12 '19 at 13:13
  • @ArturCzyżewski Sorry, but the custom function [`get_attribute_id_from_name()`](https://stackoverflow.com/questions/47518333/create-programmatically-a-variable-product-and-two-new-attributes-in-woocommerce/47844054#47844054) is a bit lighter than the woocommerce official one, and answers this question too… So yes it's answered before... I could have close this thread as duplicated, which I have not done, to allow people to answer. – LoicTheAztec Apr 12 '19 at 14:16

3 Answers3

4

You can use wc_attribute_taxonomy_id_by_name($taxonomy_name).

Artur Czyżewski
  • 705
  • 5
  • 12
  • 1
    Hi! Please explain why this is a solution to OPs code as code only answers are discouraged on SO. This would help OP and future visitors to the site. Thanks! – d_kennetz Apr 12 '19 at 17:01
  • That is a function that can allow you to get an attribute's id by name. Usually, – Henry Obiaraije May 08 '23 at 17:10
1

Woocommerce stores attributes in the table wp_woocommerce_attribute_taxonomies. Querying the database directly is not recommended but I was able to get the attribute ID using this code:

global $wpdb;
$attribute_id = $wpdb->get_var("select attribute_id from {$wpdb->prefix}woocommerce_attribute_taxonomies where attribute_name='pa_foobar'");
Robbie Lewis
  • 2,844
  • 3
  • 18
  • 29
  • 2
    Yes that SQL query is similar to the one used in my custom function `get_attribute_id_from_name()` on [**this answer thread**](https://stackoverflow.com/questions/47518333/create-programmatically-a-variable-product-and-two-new-attributes-in-woocommerce/47844054#47844054) … +1 – LoicTheAztec Apr 12 '19 at 14:15
-2

You can use that

woocommerce_get_product_terms

or

get_the_terms()

https://developer.wordpress.org/reference/functions/get_the_terms/

 global $product;
 $id = $product->get_id();
mooga
  • 3,136
  • 4
  • 23
  • 38