将这个放在WP Stack Exchange中,但是他们经常说因为它有PHP它应该在SO中,所以永远不能确定哪里最好。如果更合适,可以移动。
要显示名为“Fabrics”的自定义woocommerce产品属性,例如我已阅读过您可以执行以下操作。
$fabric_values = get_the_terms( $product->id, ‘pa_fabrics’);
foreach ( $fabric_values as $fabric_value ) {
echo $fabric_value->name;
}
然而,由于我们在整个php模板中使用了很多属性,因此有一个更短的方法。
例如,有没有办法简单地做到,“echo get_the_terms($ product-> id,'pa_fabrics');”
或者是否有一个可以添加到他们网站的功能,这样就可以回复任何产品属性,就像你在非WooCommerce网站上使用“高级自定义字段”时一样,可以像上面一样非常短的线路?
更新
在SO上找到了this thread,它提供了一种创建单个短代码的方法,可以相对轻松地获取数据。虽然这当然是一种选择,但我想看看是否有更清洁的内置方式,例如:
echo get_the_terms( $product->id, 'pa_fabrics');
或
echo $product->get_attributes('pa_fabrics');
最后一个选项看起来最干净,最理想,但会导致错误:“致命错误:未捕获错误:在我的functions.php文件中调用null中的成员函数get_attributes(),其中添加了代码。” / p>
答案 0 :(得分:5)
你的问题的答案取决于它。考虑一下你需要这么灵活。
让我们首先看看2个建议的例子有什么问题。
1)echo get_the_terms( . . .
使用函数时,了解返回类型很重要。 get_the_terms()
成功后将返回一个数组。您需要对该数组执行某些操作才能显示它。
https://developer.wordpress.org/reference/functions/get_the_terms/
2)echo $product->get_attributes(...
你正朝着正确的道路前进:)你所看到的错误告诉你$product
不是你期望的那样。 get_attributes()
是WC_Product
类的方法。您需要拥有该类的实例才能使用它。
掌握产品的一种方法是使用wc_get_product()
。
$product = wc_get_product();
现在你遇到的第二个问题是方法本身。与get_attributes()
一样,get_the_terms()
将返回一个数组。然后,您有责任显示该数据。
get_attribute()
。此方法将属性名称作为其唯一参数,并返回一个属性值字符串。
示例:
// Get a product instance. I could pass in an ID here.
// I'm leaving empty to get the current product.
$product = wc_get_product();
// Output fabrics in a list separated by commas.
echo $product->get_attribute( 'pa_fabrics' );
// Now that I have $product, I could output other attributes as well.
echo $product->get_attribute( 'pa_colors' );