在WooCommerce购物车和结帐表中显示产品自定义字段值

问题描述 投票:0回答:1

在WooCommerce中,我为每个产品添加了自定义字段“description”。我能够找到一种方法来显示标签名称和值:

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;
}

如何为此自定义字段创建,仅显示值?

php wordpress woocommerce cart custom-fields
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.