https://codewp.ai/snippet/6fz3xstkascbrtcv9oarlmelnpvxi/
Copy URL

Share this on your favorite social networks:

OR
Please log in to use this feature.
Email To Yourself Or A Developer
verified
Verified working as of March 21, 2023
GenID: 1037

Shortcode that displays the total number of sales from completed orders that a WooCommerce product with the category of "donation" has

Here's a helpful WooCommerce shortcode that displays the total sales ($) that all products in a specific category has. The use case here is that the shop owner accepts donations by selling "products". Each product has the category of "donation". This shortcode looks at all of the sales that all products have had, and allows you to output that figure on the frontend of your site.

Perfect for "We've raised X amount of {goal} amount." Note, this snippet outputs a raw integer. To make it pretty for frontend consumption, you could wrap the $total in number_format().

Original
add_shortcode('total_donations', 'total_donations');
function total_donations() {
    $args = array(
        'post_type' => 'product',
        'product_cat' => 'donation',
        'posts_per_page' => -1
    );
    $loop = new WP_Query( $args );
    $total = 0;
    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        $total += $product->get_total_sales();
    endwhile;
    wp_reset_query();
    return $total;
}

Snippet Explanation

This code calculates the total donations received in WooCommerce by summing the total sales for all products in the 'donation' category. The code uses a shortcode called 'total_donations' to display the total on any page or post in WordPress.

The "add_shortcode" function is used to register the 'total_donations' shortcode and specify the function that will be called when the shortcode is used ("total_donations").

The "total_donations" function first retrieves all products in the 'donation' category using the "WP_Query" class and a "posts_per_page" value of -1 to retrieve all products.

The function then loops through each product and retrieves the global $product variable, which contains the product object. It uses the "get_total_sales" method of the product object to retrieve the total sales for that product and adds it to a variable called "$total".

Finally, the function resets the query using the "wp_reset_query" function and returns the total donations received as the output of the shortcode.

Read More
publishLoad Prompt
preview
Make Public
share
Share Snippet
download
Export Snippet
Mode: WordPress PHP
Language: PHP
Tags:
Visibility: Public
Date:
November 22, 2022
Creator:
@James LePa...
cross