skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. If in your shortcode function code contain global $product;, then the following revisited code should work:

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

    Otherwise, you will need to provide in your question the function code for your shortcode, to be able to give you a correct working answer…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search