使产品页面中的工作简码也适用于 WooCommerce 购物车项目

Make a working shortcode in product pages work also for WooCommerce cart items

我正在尝试显示通过自定义元字段输入并通过简码输出的价格的后缀文本。

这是我的代码:

function prefix_suffix_price_html($price){
    $shortcode   = do_shortcode('[shortcode]') ;
    $psPrice     = '';
    $psPrice    .= $price;
    $psPrice    .= '<span class="suffix">'. $shortcode . '</span>';
    return $psPrice;
}
add_filter('woocommerce_get_price_html', 'prefix_suffix_price_html');
add_filter( 'woocommerce_cart_item_price', 'prefix_suffix_price_html' );

这在产品和存档页面上运行良好。

但是,它不适用于购物车商品。返回一个没有短代码内容的空 span 标签。

如果在您的短代码函数代码中包含 global $product;,那么以下重新访问的代码应该可以工作:

add_filter( 'woocommerce_get_price_html', 'add_suffix_to_product_price_html', 10, 2 );
function add_suffix_to_product_price_html( $price, $product ){
    return $price . '<span class="suffix">'. do_shortcode('[shortcode]') . '</span>';
}

add_filter( 'woocommerce_cart_item_price', 'add_suffix_to_cart_item_price_html' );
function add_suffix_to_cart_item_price_html( $price, $cart_item, $cart_item_key ){
    $product = $cart_item['data'];
    
    return $price . '<span class="suffix">'. do_shortcode('[shortcode]') . '</span>';
}

否则,您需要在问题中提供短代码的功能代码,以便能够为您提供正确的工作答案……

我现在已经省略了短代码并解决了购物车项目这样的问题:

add_filter( 'woocommerce_cart_item_price', 'add_suffix_to_cart_item_price_html' );
function add_suffix_to_cart_item_price_html( $price ){
    global $product;
    foreach( WC()->cart->get_cart() as $cart_item ){
        $product = $cart_item['data'];
        $product_id = $product->get_id(); 
        $suffix = get_post_meta( $product->get_id(), 'CUSTOMFIELDNAME', true );
        return $price . '<span class="suffix">'. $suffix . '</span>';
    }
}

这个 post 进一步帮助了我: