Last active
February 23, 2023 19:13
-
-
Save fysalyaqoob/96419530a85da8ec1f9147861152c0bb to your computer and use it in GitHub Desktop.
WooCommerce Shortcode to show products that are dynamically selected based on sales velocity and total sales
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fy_product_loop_shortcode( $atts ) { | |
$atts = shortcode_atts( array( | |
'limit' => 12, | |
), $atts ); | |
$args = array( | |
'status' => 'publish', | |
'limit' => -1, | |
); | |
$products = wc_get_products($args); | |
foreach ($products as $product) { | |
$sales = $product->get_total_sales(); | |
$sales_velocity = $sales / max(1, $product->get_date_created()->diff(new DateTime())->days); | |
$total_sales = $sales; | |
$product->sales_velocity = $sales_velocity; | |
$product->total_sales = $total_sales; | |
} | |
usort($products, function($a, $b) { | |
if ($a->sales_velocity === $b->sales_velocity) { | |
return $b->total_sales - $a->total_sales; | |
} | |
return $b->sales_velocity - $a->sales_velocity; | |
}); | |
$selected_products = array_slice($products, 0, $atts['limit']); | |
ob_start(); | |
if ($selected_products) { | |
global $product; | |
// Set up the template loop | |
wc_set_loop_prop( 'name', 'product-loop' ); | |
wc_set_loop_prop( 'columns', 4 ); | |
wc_get_template_part( 'loop/loop-start' ); | |
foreach ($selected_products as $product) { | |
wc_setup_product_data( $product->get_id() ); | |
wc_get_template_part( 'content', 'product' ); | |
wc_reset_loop(); | |
} | |
wc_get_template_part( 'loop/loop-end' ); | |
} | |
return ob_get_clean(); | |
} | |
add_shortcode( 'fy_product_loop', 'fy_product_loop_shortcode' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shortcode: [fy_product_loop limit="12"]