php - 在 WooCommerce 购物车和结帐表中显示产品自定义字段值
问题描述
在 WooCommerce 中,我为每个产品添加了一个自定义字段“描述”。我能够找到一种同时显示标签名称和值的方法:
add_filter( 'woocommerce_add_cart_item_data', 'save_days_field', 10, 2 );
function save_days_field( $cart_item_data, $product_id ) {
$special_item = get_post_meta( $product_id , 'description',true );
if(!empty($special_item)) {
$cart_item_data[ 'description' ] = $special_item;
// below statement make sure every add to cart action as unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'description', $special_item );
}
return $cart_item_data;
}
// Render meta on cart and checkout
add_filter( 'woocommerce_get_item_data','rendering_meta_field_on_cart_and_checkout', 10, 2 );
function rendering_meta_field_on_cart_and_checkout( $cart_item_data, $cart_item ) {
if( isset( $cart_item['description'] ) ) {
$cart_item_data[] = array( "name" => __( "Description", "woocommerce" ), "value" => $cart_item['description'] );
}
return $cart_item_data;
}
现在我只需要在购物车和结帐表中显示此自定义字段的值(而不是标签名称“描述”)。我需要用 显示<small>
,就像我用这段代码显示的属性一样:
add_filter('woocommerce_cart_item_name', 'wp_woo_cart_attributes', 10, 2);
function wp_woo_cart_attributes($cart_item, $cart_item_key){
$productId = $cart_item_key['product_id'];
$product = wc_get_product($productId);
$taxonomy = 'pa_color';
$value = $product->get_attribute($taxonomy);
if ($value) {
$label = get_taxonomy($taxonomy)->labels->singular_name;
$cart_item .= "<small>$value</small>";
}
return $cart_item;
}
我怎样才能为这个自定义字段制作它,只显示值?
解决方案
您不需要包含产品自定义字段作为自定义购物车项目数据,因为它可以从产品对象(或产品 ID)直接访问。
注意:在购物车项目变量$cart_item
中,WC_Product
对象被包含并使用$cart_item['data']
.
尝试以下方法在购物车和结帐页面中的商品名称后添加自定义字段:
// Display in cart and checkout pages
add_filter( 'woocommerce_cart_item_name', 'customizing_cart_item_name', 10, 3 );
function customizing_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
$product = $cart_item['data']; // Get the WC_Product Object
if ( $value = $product->get_meta('description') ) {
$product_name .= '<small>'.$value.'</small>';
}
return $product_name;
}
要在订单和电子邮件通知中显示它,请使用:
// Display in orders and email notifications
add_filter( 'woocommerce_order_item_name', 'customizing_order_item_name', 10, 2 );
function customizing_order_item_name( $product_name, $item ) {
$product = $item->get_product(); // Get the WC_Product Object
if ( $value = $product->get_meta('description') ) {
$product_name .= '<small>'.$value.'</small>';
}
return $product_name;
}
代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。
推荐阅读
- android - 如何使用 Android 自动填充 API
- javascript - 偶数访问时显示缓存的网页,奇数访问时在前端获取
- nhibernate - 如何在控制台应用程序中调用它的同一线程上继续异步方法调用(SynchronizationContext?)
- python - 修复试图在 for 循环中的切片副本上设置值
- css - 我的网站引导列 (col-md-4) 在某些地方溢出,我似乎无法隔离问题
- html - 有谁知道如何在没有文本拉伸背景或文本低于图像的情况下获得正确大小的图像文本?
- amazon-web-services - 如何将变量(环境属性)从 CodeBuild 传递到 CodePipeline 中的 Beanstalk 应用程序?
- extjs - Extjs animateUnderline 示例
- python - 为什么数据不使用 python 发送到 KAFKA 主题?
- asp.net-core - .NetCore 项目中与视图的模型绑定给出了对象引用空错误——