1

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
claudio
  • 33
  • 4

2 Answers2

1

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…

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Thank you very much for your help. Your code works so far except for the shopping cart. Unfortunately, I cannot display the shortcode code, as it is generated via JetEngine metabox. It seems that global $product is not integrated there. – claudio Apr 16 '21 at 06:24
0

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

claudio
  • 33
  • 4