在WooCommerce Shopping Cart页面的每个产品下面添加Shipping类

时间:2018-01-20 07:58:25

标签: php wordpress woocommerce cart shipping

我已为我的产品配置送货课程。但我想在购物车页面中的每个产品下面显示它们。像这样:

enter image description here

可以通过编辑PHP来完成吗?

1 个答案:

答案 0 :(得分:2)

要在购物车页面中显示产品运输类名称,有很多方法可以执行此操作:

1)使用隐藏在 woocommerce_cart_item_name 过滤器挂钩中的自定义函数,这样:

add_filter( 'woocommerce_get_item_data', 'shipping_class_in_item_name', 20, 2 );
function shipping_class_in_item_name( $cart_data, $cart_item ) {

    $custom_items = array();

    $product = $cart_item['data']; // Get the WC_Product object instance
    $shipping_class_id = $product->get_shipping_class_id(); // Shipping class ID
    $shipping_class_term = get_term( $shipping_class_id, 'product_shipping_class' );
    $label = __( 'Shipping class', 'woocommerce' );

    // Checking (To display it in checkout page too, remove below " || is_checkout()" )
    if( empty( $shipping_class_id ) || is_checkout() )
        return $cart_data; // Return default cart dat (in case of)

    // If product or variation description exists we display it
    $custom_items[] = array(
        'key'      => $label,
        'display'  => $shipping_class_term->name,
    );

    // Merging shipping class name and product variation attributes + values (if there are some)
    if( ! empty( $cart_data ) ) $custom_items = array_merge( $custom_items, $cart_data );

    return $custom_items;
}

代码进入活动子主题(或活动主题)的function.php文件。

此代码经过测试并有效。

2)使用连接在 woocommerce_cart_item_name 过滤器钩子中的自定义函数,这样:

add_filter( 'woocommerce_cart_item_name', 'shipping_class_in_item_name', 20, 3);
function shipping_class_in_item_name( $item_name, $cart_item, $cart_item_key ) {
    // Only in cart page (remove the line below to allow the display in checkout too)
    if( ! ( is_cart() || is_checkout() ) ) return $item_name;

    $product = $cart_item['data']; // Get the WC_Product object instance
    $shipping_class_id = $product->get_shipping_class_id(); // Shipping class ID
    $shipping_class_term = get_term( $shipping_class_id, 'product_shipping_class' );

    if( empty( $shipping_class_id ) )
        return $item_name; // Return default product title (in case of)

    $label = __( 'Shipping class', 'woocommerce' );

    return $item_name . '<br>
        <p class="item-shipping_class" style="margin:12px 0 0;">
            <strong>' .$label . ': </strong>' . $shipping_class_term->name . '</p>';
}

代码进入活动子主题(或活动主题)的function.php文件。

经过测试和工作。