Skip Navigation

[Resolved] Display onsale custom shortcode

This thread is resolved. Here is a description of the problem and solution.

Problem:
Display onsale custom shortcode

Solution:
To get the product object based on the current post in the view's loop, I've added the following line of code as you can see with the above shortcode:

$product = wc_get_product($post->ID);    

You can find the proposed solution in this case with the following reply:
https://toolset.com/forums/topic/display-onsale-custom-shortcode/page/2/#post-1779645

Relevant Documentation:

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 16 replies, has 2 voices.

Last updated by ralphG 1 month, 1 week ago.

Assigned support staff: Minesh.

Author
Posts
#1779645

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

I'm sorry for a little late reply here as the queue was really busy.

Can you please check now: hidden link

You were using the wrong product object to calculate the percentage.

I've adjusted the shortcode code as given under:

function show_onsale_percentage_shortcode() {
    global $post;
	
    $percent = 0;
    if($post){
		$product = wc_get_product($post->ID);	
        if ( $product->is_on_sale() && $product->is_type('simple') ) {
            $percent = floor((1 - ( $product->get_sale_price() / $product->get_regular_price() )) * 100);
        }   
    }
    return $percent;
}
add_shortcode('onsale-percent', 'show_onsale_percentage_shortcode');

To get the product object based on the current post in the view's loop, I've added the following line of code as you can see with the above shortcode:

$product = wc_get_product($post->ID);	

Can you please confirm it works at your end as well.

#1780005

It was this simple...

My issue is resolved now. Thank you a lot!