0

The sale price column in woo commerce admin product list is not sortable. I am getting the sale priced product now, but wanna sort them.

add_filter( 'manage_edit-product_columns', 'onsale_product_column', 10);
function onsale_product_column($columns){
    $new_columns = [];
    foreach( $columns as $key => $column ){
        $new_columns[$key] = $columns[$key];
        if( $key == 'product_cat' ) {
            $new_columns['onsale'] = __( 'Sale Price','woocommerce');
        }
    }
    return $new_columns;
}

add_action( 'manage_product_posts_custom_column', 'onsale_product_column_content', 10, 2 );
function onsale_product_column_content( $column, $post_id ){
    if( $column == 'onsale' ){
        global $post, $product;

        // Excluding variable and grouped products
        if( is_a( $product, 'WC_Product' ) && ! $product->is_type('grouped') &&
        ! $product->is_type('variable') && $product->is_on_sale() ) {
            echo strip_tags( wc_price( $product->get_sale_price() ) );
        }
    }
}
  • You should try something like this - https://stackoverflow.com/questions/69051715/woocommerce-how-to-sort-products-by-last-modified-date/69052764#69052764 – Rajeev Singh Sep 21 '21 at 05:53

1 Answers1

0

Simply add the following on top of your existing code, so that you can make that column sortable and sort by that value (untested):

add_filter( 'manage_edit-product_sortable_columns', 'bbloomer_onsale_product_column_sort' );

function bbloomer_onsale_product_column_sort( $columns ) {
    $columns['onsale'] = 'onsale';
    return $columns;
}

add_action( 'pre_get_posts', 'bbloomer_onsale_product_sort' );

function bbloomer_onsale_product_sort( $query ) {
    if ( ! is_admin() ) return; 
    $orderby = $query->get( 'orderby');
    if ( 'onsale' == $orderby ) {
        $query->set( 'meta_key', '_sale_price' );
        $query->set( 'orderby', 'meta_value_num' );
    }
}
businessbloomer
  • 1,115
  • 7
  • 11