Halloween Sale 15% off Ends in See the plans
PHP

"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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.