我使用 woocommerce 插件创建了一个可变产品。在变量产品中,我创建了一个自定义属性“许可证持续时间”,其值为“3 个月 | 6 个月 | 1 年 | 生命周期”。
现在我想在自定义单个产品模板上显示此属性。
我尝试过以下解决方案
1.
$licenseDurations = get_the_terms( $post->ID, 'attribute_license-duration' );
这显示了以下内容
var_dump($licenseDurations);
`
object(WP_Error)[558]
public 'errors' =>
array (size=1)
'invalid_taxonomy' =>
array (size=1)
0 => string 'Invalid taxonomy' (length=16)
public 'error_data' =>
array (size=0)
empty`
和
2.
global $product;
$licenseDuration = $product->get_attribute( 'License Duration' ); // Here I also tried attribute slug `attribute_license-duration` instead of `License Duration` but no use
参考:https://stackoverflow.com/a/13454788/2758870
和
3.
global $product;
$licenseDurations = get_the_terms( $product->id, 'License Duration');
foreach ( $licenseDurations as $licenseDuration )
{
echo $licenseDuration->name;
}
在上述两种情况下我什么也没得到,因为
$product;
正在返回null
于var_dump($product)
4.我也尝试过此代码http://isabelcastillo.com/woocommerce-product-attributes-functions
通过直接调用
isa_woo_get_one_pa()
我想显示值。但没有运气。
这里的任何人请帮忙...
您可以尝试以下方法
1.
get_post_meta
获取产品属性
$attr = get_post_meta( 123, '_product_attributes' ); // replace 123 with the actual product id
print_r( $attr );
2.或者你可以创建一个产品对象,然后使用
get_attributes
方法
$p = new WC_Product( 123 ); // // replace 123 with the actual product id
print_r( $p->get_attributes() );
不确定woocommerce是否有变化,上面没有给出属性值。此页面的以下帖子给出了正确答案
// 将
pa_attribute
替换为您的属性名称,但保留 pa_
前缀pa_weight
$fabric_values = get_the_terms( $product->id, 'pa_attribute');
foreach ( $fabric_values as $fabric_value ) {
echo $fabric_value->name;
}
以下是所有产品属性列表:
$product_attributes = get_post_meta( $post->ID, '_product_attributes' );
foreach ( $product_attributes as $group_attributes ) {
foreach ( $group_attributes as $attributes ) {
echo $attributes['name'].'=>'.$attributes['value'];
}
}