Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vovadocent/7b4a58d7d9e8abb3c68dd82607c2bbf0 to your computer and use it in GitHub Desktop.
Save vovadocent/7b4a58d7d9e8abb3c68dd82607c2bbf0 to your computer and use it in GitHub Desktop.
Woocommerce order admin list custom field filter
<?php
//// wc order admin list custom field filter ////
function woo_orders_list_custom_filter($query) {
$post_type = !empty($_GET['post_type']) ? filter_input(INPUT_GET, 'post_type') : false;
$lctn = !empty($_GET['lctn']) ? filter_input(INPUT_GET, 'lctn') : false;
if (is_admin() && ($post_type == 'shop_order' && $query->is_main_query() && $lctn > 0)) {
$meta = $query->get('meta_query');
$meta[] = array('key' => 'delivery_name', 'value' => $lctn, 'compare' => '=');
$query->set('meta_query', $meta);
}
}
add_action('pre_get_posts', 'woo_orders_list_custom_filter');
add_action('wp_ajax_locationsFilterSelect', 'locationsFilterSelect');
function locationsFilterSelect() {
global $wpdb;
$lctn = filter_input(INPUT_POST, 'lctn');
$out = "<select name='lctn' id='filter_by_location'><option value='0'>All Locations</option>";
$ids_res = $wpdb->get_results("SELECT DISTINCT pm.meta_value FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON (p.ID = pm.post_id AND p.post_type = 'shop_order') WHERE pm.meta_key = 'delivery_name'");
if ($ids_res) {
$ids = array_map(function($e) {
return $e->meta_value;
}, $ids_res);
$posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID IN (" . implode(',', $ids) . ") ORDER BY post_title ASC");
foreach ($posts as $p) {
$sel = $lctn == $p->ID ? 'selected="selected"' : false;
$out .= "<option $sel value='$p->ID'>$p->post_title</option>";
}
}
echo $out . "</select>";
exit();
}
//// end of wc order admin list custom field filter ////
///// js section admin order list ///////
if ($('.cp-shop_order').length > 0) {
$.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: "action=locationsFilterSelect&lctn="+takeGetParam('lctn'),
beforeSend: function () {
},
success: function (resp) {
$('#filter-by-date').after(resp);
}
});
}
/// end of admin order list ///
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment