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 support ticket is created 3 years, 7 months ago. There's a good chance that you are reading advice that it now obsolete.

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.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 16 replies, has 2 voices.

Last updated by ralphG 3 years, 7 months ago.

Assisted by: 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!

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.