Ste*_*ght 7 php wordpress product cart woocommerce
更新(与作者评论相关):
我想自定义WooCommerce cart.php以显示一些使用Essential Grid高级插件在产品页面上正常工作的元数据.
我想展示一些产品的属性字段,也是我与创造了一些自定义的元字段元场创造者的基本电网插件.
为了测试,我使用'Height'属性(so 'pa_height')和'Age'slug所在的自定义字段'eg-age-cal'.
目前,我已尝试使用以下内容:
<?php echo get_post_meta($product_id, 'pa_height', true );?>
Run Code Online (Sandbox Code Playgroud)
并且:
<?php echo get_post_meta($product_id, 'eg-age-cal', true );?>
Run Code Online (Sandbox Code Playgroud)
但这些似乎不起作用.
我已设法使用以下代码:
<?php echo get_post_meta($product_id, '_regular_price', true );?>
Run Code Online (Sandbox Code Playgroud)
所以我知道代码正在运行.
我只需要帮助解决问题,如何从这些自定义属性和自定义字段中获取值.
谢谢.
更新(与WC 3+兼容)
在下面的评论中进行了解释之后,我发现您正在使用Essential Grid高级插件 (商业插件)来创建一些与wooCommerce产品相关的自定义字段和属性。
在这一点上,我无能为力,因为我以前从未使用过此插件,并且不知道数据在数据库中此插件中的存储位置。
我认为您不能使用常规的WordPress / WooCommerce函数来获取此数据,这就是您将无法像往常一样获取任何数据的原因……get_post_meta()
寻求帮助的最佳方法是:
-搜索/探索您的数据库以获取自定义字段数据。
-搜索/询问Essential Grid插件作者支持线程。
我的原始答案:
对于产品中定义的属性,将get_post_meta()函数与$product_id变量一起使用,您需要以这种方式使用它来获取所需的数据(这是值的数组):
// 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 );
Run Code Online (Sandbox Code Playgroud)
您还可以通过以下方式使用函数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 );
Run Code Online (Sandbox Code Playgroud)
所有代码都经过测试并且可以正常工作。
现在,Cookies和会话中已设置
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>';
}
}
Run Code Online (Sandbox Code Playgroud)
这将显示CART中每个产品的值的属性数组。
基于此线程的解决方案,使用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>';
}
}
Run Code Online (Sandbox Code Playgroud)
参考文献:
| 归档时间: |
|
| 查看次数: |
14982 次 |
| 最近记录: |