Created
May 13, 2022 15:56
-
-
Save mrkaluzny/5c9e08fdca81ec23a06a60d648914cca to your computer and use it in GitHub Desktop.
WooCommerce -> Popularity custom sorting based on last 30days of 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
<?php | |
if (!wp_next_scheduled('set_last_month_product_sales_hook')) { | |
wp_schedule_event(time(), 'daily', 'set_last_month_product_sales_hook'); | |
} | |
add_action('set_last_month_product_sales_hook', 'cc_set_last_month_sales'); | |
function cc_set_last_month_sales() | |
{ | |
$orders = wc_get_orders( | |
array( | |
'limit' => -1, | |
'status' => array_map('wc_get_order_status_name', wc_get_is_paid_statuses()), | |
'date_after' => date('Y-m-d', strtotime('-1 month')), | |
'return' => 'ids', | |
) | |
); | |
$identifiers = array(); | |
foreach ($orders as $order) { | |
$items = wc_get_order($order)->get_items(); | |
foreach ($items as $item) { | |
array_push($identifiers, $item->get_product_id()); | |
}; | |
}; | |
$counted_sales = array_count_values($identifiers); | |
$keys = array(); | |
foreach ($counted_sales as $key => $val) { | |
array_push($keys, $val); | |
add_post_meta($key, 'wc_last_month_sales', $val); | |
} | |
}; | |
function cc_add_postmeta_ordering_args($sort_args) | |
{ | |
$orderby_value = isset($_GET['orderby']) ? wc_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby')); | |
switch ($orderby_value) { | |
case 'popularity': | |
$sort_args['orderby'] = 'meta_value'; | |
$sort_args['order'] = 'asc'; | |
$sort_args['meta_key'] = 'wc_last_month_sales'; | |
break; | |
} | |
return $sort_args; | |
} | |
add_filter('woocommerce_get_catalog_ordering_args', 'cc_add_postmeta_ordering_args'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I add the code to theme functions.php is not work, how can I do? waiting for your reply, many thanks