Search code examples
phpwordpresswoocommercehook-woocommerceshortcode

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


I am trying to display a suffix text for the price entered via a custom meta field and output via a shortcode.

Here is my code:

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' );

This works fine on the product and archive pages.

However, it does not work for cart items. The an empty span tag is returned without the content of the shortcode.


Solution

  • I now have omitted the shortcode and solved it for the shopping cart items like this:

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

    This post has helped me further: Get product custom field values as variables in WooCommerce