WooCommerce admin filter products by image
A client recently asked me to add a filter to the WooCommerce admin products list so they can filter items based on if the item had an image or not. This allowed them to easily find products which had missing images so they could correct.
Why not take a look how to filter by on sale items?
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
/* * Woocommerce Filter by on sale */ function custom_woocommerce_filter_by_onsale($output) { global $wp_query; $selected = filter_input(INPUT_GET, 'product_sale', FILTER_VALIDATE_INT); if ($selected == false) { $selected = 0; } $output .= ' <select id="dropdown_product_sale" name="product_sale"> <option value="">Filter by sale</option> <option selected="selected" value="1">On sale</option> <option selected="selected" value="2">Not on sale</option> </select> '; return $output; } add_action('woocommerce_product_filters', 'custom_woocommerce_filter_by_onsale'); /* * Woocommerce Filter by on sale where statement */ function custom_woocommerce_filter_by_onsale_where_statement($where) { global $wp_query, $wpdb; // Get selected value $selected = filter_input(INPUT_GET, 'product_sale', FILTER_VALIDATE_INT); // Only trigger if required if (!is_admin() || get_query_var('post_type') != "product" || !$selected) { return $where; } $productsIDs = []; if ($selected == 1) { $querystr = ' SELECT p.ID, p.post_parent FROM ' . $wpdb->posts . ' p WHERE p.ID IN ( SELECT post_id FROM ' . $wpdb->postmeta . ' pm WHERE pm.meta_key = "_sale_price" AND pm.meta_value > \'\' ) '; $pageposts = $wpdb->get_results($querystr, OBJECT); $productsIDs = array_map(function($n){ return $n->post_parent > 0 ? $n->post_parent : $n->ID; }, $pageposts); } elseif ($selected == 2) { $querystr = ' SELECT p.ID, p.post_parent FROM ' . $wpdb->posts . ' p WHERE p.ID NOT IN ( SELECT post_id FROM ' . $wpdb->postmeta . ' pm WHERE pm.meta_key = "_sale_price" AND pm.meta_value > \'\' ) '; $pageposts = $wpdb->get_results($querystr, OBJECT); $productsIDs = array_map(function($n){ return $n->post_parent > 0 ? $n->post_parent : $n->ID; }, $pageposts); } $where .= ' AND ' . $wpdb->posts . '.ID IN (' . implode(",", $productsIDs) . ') '; return $where; } add_filter('posts_where' , 'custom_woocommerce_filter_by_onsale_where_statement'); |
This code is provided as it and may require changes to work for your needs.