"On Sale" Filter in the Admin Products List
Adds a dropdown to the admin Products list to show only products that are currently on sale, or only those that are not.
Opens WPIDE on
Code
add_action( 'restrict_manage_posts', function ( $post_type ) {
if ( 'product' !== $post_type ) {
return;
}
$current = isset( $_GET['wpide_on_sale'] ) ? sanitize_key( wp_unslash( $_GET['wpide_on_sale'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
echo '<label for="wpide-on-sale" class="screen-reader-text">' . esc_html( 'Filter by sale' ) . '</label>';
printf(
'<select name="wpide_on_sale" id="wpide-on-sale"><option value="">%1$s</option><option value="yes" %2$s>%3$s</option><option value="no" %4$s>%5$s</option></select>',
esc_html( 'Sale status' ),
selected( $current, 'yes', false ),
esc_html( 'On sale' ),
selected( $current, 'no', false ),
esc_html( 'Not on sale' )
);
} );
add_action( 'pre_get_posts', function ( $query ) {
if ( ! is_admin() || ! $query->is_main_query() || 'product' !== $query->get( 'post_type' ) || empty( $_GET['wpide_on_sale'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
$ids = wc_get_product_ids_on_sale();
$ids = array_values( array_unique( array_filter( array_map( 'wp_get_post_parent_id', $ids ) ) + $ids ) );
if ( 'yes' === $_GET['wpide_on_sale'] ) { // phpcs:ignore WordPress.Security.NonceVerification
$query->set( 'post__in', $ids ? $ids : array( 0 ) );
} else {
$query->set( 'post__not_in', $ids );
}
} );
Notes
Uses WooCommerce's cached list of products on sale, so filtering is fast.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.