更新(与 WC 3+ 兼容)
在您在下面的评论中解释之后,我发现您正在使用Essential Grid premium plugin(一个商业插件)来创建一些与您的 wooCommerce 产品相关的自定义字段和属性。
在这一点上,我无能为力,因为我以前从未使用过这个插件,而且我不知道这个插件中的数据存储在数据库中的什么位置。
我认为你不能使用常用的 WordPress/WooCommerce 函数来获取这些数据,这就是你不会像往常一样使用get_post_meta() 获取任何数据的原因......
获得帮助的最佳方式是:
- 搜索/探索您的数据库中的自定义字段数据。
- 在 Essential Grid 插件作者支持线程中搜索/询问。
我原来的回答:
对于您的产品中定义的属性,使用带有 $product_id 变量的 get_post_meta() 函数,您需要这样使用它获取您想要的数据(这是一个值数组):
// getting the defined product attributes
$product_attr = get_post_meta( $product_id, '_product_attributes' );
// displaying the array of values (just to test and to see output)
echo var_dump( $product_attr );
你也可以使用函数get_attributes()(更推荐),这样:
// Creating an object instance of the product
$_product = new WC_Product( $product_id );
// getting the defined product attributes
$product_attr = $_product->get_attributes();
// displaying the array of values (just to test and to see output)
echo var_dump( $product_attr );
所有代码都经过测试并且可以运行。
现在购物车数据已在 Cookie 和会话中设置,您需要使用 WC()->cart 语法来获取购物车数据和商品
所以你可以使用这种代码来获取购物车中的物品(产品):
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
if(!empty($product)){
// getting the defined product attributes
$product_attr = $_product->get_attributes();
// displaying the attributes array of values (just to test and to see output)
echo var_dump( $product_attr ) . '<br>';
}
}
这将显示 CART 中每个产品的属性值数组。
一个基于this thread的解决方案,在同一代码sn-p中使用wc_get_product_terms()来获取你的属性:
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
if(!empty($product)){
// compatibility with WC +3
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
// Getting "height" product attribute
$myAttribute = array_shift( wc_get_product_terms( $product_id, 'pa_height', array( 'fields' => 'names' ) ) );
echo $myAttribute . '<br>';
}
}
参考文献: