You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WooCommerce迷你购物车区块的商品添加自定义类?

解决WooCommerce迷你购物车区块添加自定义类的问题

因为迷你购物车是基于Gutenberg JS渲染的区块,仅靠PHP钩子无法完成类名添加,需要前后端配合实现:

步骤1:PHP端传递产品标识数据到前端

先把产品的is_alcohol标记同步到购物车项的JSON数据中,让前端JS能获取判断依据:

// 将is_alcohol数据添加到购物车项的JSON输出
function custom_add_cart_item_json_data( $item_data, $cart_item ) {
    if ( isset( $cart_item['data'] ) ) {
        $product = $cart_item['data'];
        $is_alcohol = get_post_meta( $product->get_id(), 'is_alcohol', true );
        
        if ( $is_alcohol === 'yes' ) {
            $item_data['is_alcohol'] = true;
        }
    }
    return $item_data;
}
add_filter( 'woocommerce_cart_item_to_json', 'custom_add_cart_item_json_data', 10, 2 );

可选:为确保数据在购物车会话中稳定保留,添加以下钩子:

// 保存is_alcohol数据到购物车项会话
function custom_save_cart_item_alcohol_data( $cart_item_data, $product_id ) {
    $is_alcohol = get_post_meta( $product_id, 'is_alcohol', true );
    
    if ( $is_alcohol === 'yes' ) {
        $cart_item_data['is_alcohol'] = true;
    }
    return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'custom_save_cart_item_alcohol_data', 10, 2 );

步骤2:JS端修改迷你购物车项类名

  1. 在主题functions.php或插件中注册并加载自定义JS脚本:
// 注册迷你购物车自定义JS
function custom_enqueue_minicart_script() {
    if ( is_frontend() ) {
        wp_enqueue_script(
            'custom-minicart-class',
            get_stylesheet_directory_uri() . '/js/custom-minicart-class.js', // 替换为你的JS文件实际路径
            array( 'wp-hooks', 'wc-blocks', 'wp-element' ),
            wp_get_theme()->get('Version'),
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'custom_enqueue_minicart_script' );
  1. 创建custom-minicart-class.js文件,内容如下:
// 为酒类商品添加自定义类
wp.hooks.addFilter(
    'woocommerce.block.cart.item.classes',
    'custom/minicart/add-alcohol-class',
    ( classes, item ) => {
        if ( item.is_alcohol ) {
            classes.push( 'is_alcohol' );
        }
        return classes;
    }
);

注意事项

  • 确保JS文件路径正确,若为插件开发,将get_stylesheet_directory_uri()替换为plugin_dir_url(__FILE__)类路径。
  • 测试前清空浏览器缓存、WooCommerce缓存,确保代码生效。

内容的提问来源于stack exchange,提问作者Drahcir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:12:38