Show best selling products in Last weeks
-
I have a Woocommerce site with Astra theme. there is an inbuilt shortcode to display best selling prodcuts , but i only wanted to display last weeks best selling prodcuts so i tried to write a custom shortcode to display there by manually with codes but when i try to add date range its shows latest products rather than last week best selling if i dont have any products sold in last week it still shows the new product i added the last week i will share my code he
function display_best_selling_products_shortcode($atts) { ob_start(); // Set the date range to 1 week ago $date_range = strtotime('-2 year'); // Get the products with the highest sales count within the date range $products = wc_get_products(array( 'post_type' => 'product', 'posts_per_page' => 4, 'orderby' => 'meta_value_num', 'meta_key' => 'total_sales', 'order' => 'DESC', 'date_query' => array( array( 'after' => date('Y-m-d', $date_range), 'inclusive' => true, ), ), )); echo '<div class="main-best-sell-div">'; // Check if there are any best-selling products if ($products) { foreach ($products as $product) { // Get product information $product_id = $product->get_id(); $product_name = $product->get_name(); $product_link = get_permalink($product_id); $product_image = $product->get_image('full'); $product_price = $product->get_price(); $regular_price = $product->get_regular_price(); $sale_price = $product->get_sale_price(); $savings_percent = round((($regular_price - $sale_price) / $regular_price) * 100); $sales_count = get_post_meta($product_id, 'total_sales', true); echo '<div class="single-product-div wc-block-grid__product">'; echo '<div class="product-image wc-block-grid__product-image">'; echo $product_image; echo '</div>'; echo '<div class="prod-tit-div wc-block-grid__product-title"><a class="prod-tit" href="' . $product_link . '">' . $product_name . '</a></div>'; echo '<div class="wc-block-grid__product-onsale best-prod-sale"> <span aria-hidden="true">Sale</span> <span class="screen-reader-text">Product on sale</span> </div>'; echo '<span class="price">'; if ($product->is_on_sale()) { echo '<del>' . wc_price($regular_price) . '</del>'; echo '<ins>' . wc_price($sale_price) . '</ins>'; echo '<span class="savings woo-sale-text"> Save ' . $savings_percent . '%</span>'; } else { echo wc_price($product_price); } echo '</span>'; echo '<div class="sales-count">' . sprintf(__('Sales: %d', 'woocommerce'), $sales_count) . '</div>'; echo '</div>'; } } else { echo 'No best-selling products found.'; } echo '</div>'; return ob_get_clean(); } add_shortcode('test_short', 'display_best_selling_products_shortcode');
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
The topic ‘Show best selling products in Last weeks’ is closed to new replies.