【问题标题】:Woocommerce get product attribute ID using nameWoocommerce 使用名称获取产品属性 ID
【发布时间】:2018-10-09 21:22:44
【问题描述】:

我想使用属性名称获取 Woocommerce 产品属性的 ID。例如pa_foobar

我知道产品属性是分类法,但 get_taxonomy() 不返回分类法 ID。我找不到执行此操作的 Woocommerce 功能。

【问题讨论】:

  • 这个问题已经在this answer thread回答了
  • @LoicTheAztec 不正确,您无法在那里找到最佳解决方案(使用 wc_attribute_taxonomy_id_by_name('pa_foobar'))。
  • @ArturCzyżewski 抱歉,但自定义函数 get_attribute_id_from_name() 比 woocommerce 官方函数要轻一些,并且也回答了这个问题......所以是的,它之前已经回答过......我可以关闭这个线程重复,我没有做过,让人们回答。

标签: php wordpress woocommerce custom-taxonomy


【解决方案1】:

您可以使用wc_attribute_taxonomy_id_by_name($taxonomy_name)

【讨论】:

  • 嗨!请解释为什么这是 OPs 代码的解决方案,因为在 SO 上不鼓励仅代码答案。这将有助于 OP 和未来的网站访问者。谢谢!
【解决方案2】:

Woocommerce 将属性存储在表 wp_woocommerce_attribute_taxonomies 中。不建议直接查询数据库,但我可以使用以下代码获取属性 ID:

global $wpdb;
$attribute_id = $wpdb->get_var("select attribute_id from {$wpdb->prefix}woocommerce_attribute_taxonomies where attribute_name='pa_foobar'");

【讨论】:

  • 是的,SQL 查询类似于我在this answer thread 上的自定义函数get_attribute_id_from_name() 中使用的查询... +1
【解决方案3】:

你可以使用它

woocommerce_get_product_terms

get_the_terms()

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

 global $product;
 $id = $product->get_id();

【讨论】:

  • 这没有回答问题。我想获取产品属性 ID,而不是产品 ID。此时,该属性甚至可能未分配给产品。
  • 你上面提到的两个函数不返回产品属性ID。它们返回属性术语。
  • 你见过这个 $terms = wp_get_object_terms( $post->ID, $taxonomy );
  • 如果该属性尚未分配给产品怎么办?
猜你喜欢
  • 2020-11-02
  • 2019-04-04
  • 2014-07-04
  • 2020-07-20
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多