skip to Main Content

I am using a snippet to show how many items sold for the product in the frontend which displays perfectly.

add_action( 'woocommerce_single_product_summary', 'wp_product_sold_count', 11 );
function wp_product_sold_count() {
global $product;
$total_sold = get_post_meta( $product->id, 'total_sales', true );
if ( $total_sold ) echo '
' . sprintf( __( 'Sold', 'woocommerce' ), $total_sold ) . '

';
}

Now what am trying to show in the product page is, how many items were sold in the past x days.

Is there any snippet that I can use to do so?

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    So I was able to do this via ChatGPT and I got it to work. So here is the final code that worked for me:

    add_action('woocommerce_single_product_summary', 'wp_product_sold_last_10_days', 9);
    
    if (!function_exists('wp_product_sold_last_10_days')) {
        function wp_product_sold_last_10_days() {
            global $product;
    
            if (!$product) {
                return;
            }
    
            // Calculate the number of sales in the past 10 days
            $date_from = date('Y-m-d H:i:s', strtotime('-10 days'));
            $date_to = date('Y-m-d H:i:s');
            $sales_in_past_10_days = get_sales_in_date_range($product->get_id(), $date_from, $date_to);
    
            // Display the sales count for the last 10 days
            if ($sales_in_past_10_days) {
                echo '
                <p">
                    <td>
                        <span>Sold Last 10 Days:</span><strong> ' . sprintf(__('%s', 'woocommerce'), $sales_in_past_10_days) . '</strong>
                    </td>
                </p>
                ';
            }
        }
    }
    
    if (!function_exists('get_sales_in_date_range')) {
        function get_sales_in_date_range($product_id, $date_from, $date_to) {
            global $wpdb;
    
            $results = $wpdb->get_var($wpdb->prepare("
                SELECT SUM(order_item_meta.meta_value) FROM {$wpdb->prefix}woocommerce_order_items as order_items
                LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
                LEFT JOIN {$wpdb->prefix}posts as posts ON order_items.order_id = posts.ID
                WHERE order_item_meta.meta_key = '_qty'
                AND order_item_meta.order_item_id IN (
                    SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_itemmeta
                    WHERE meta_key = '_product_id' AND meta_value = %d
                )
                AND posts.post_type = 'shop_order'
                AND posts.post_status IN ('wc-completed', 'wc-processing', 'wc-on-hold')
                AND posts.post_date BETWEEN %s AND %s
            ", $product_id, $date_from, $date_to));
    
            return $results ? $results : 0;
        }
    }
    

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