首页 > 解决方案 > 在 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;
}

我怎样才能为这个自定义字段制作它,只显示值?

标签: phpwordpresswoocommercecartcustom-fields

解决方案


您不需要包含产品自定义字段作为自定义购物车项目数据,因为它可以从产品对象(或产品 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 文件中。测试和工作。


推荐阅读