Sortable Total Sales Column for Products
Adds a "Sales" column to the admin products list showing how many units each product has sold, and lets you sort by it.
Opens WPIDE on
Code
add_filter( 'manage_edit-product_columns', function ( $columns ) {
$columns['wpide_sales'] = 'Sales';
return $columns;
}, 20 );
add_action( 'manage_product_posts_custom_column', function ( $column, $post_id ) {
if ( 'wpide_sales' === $column ) {
$product = wc_get_product( $post_id );
echo $product ? (int) $product->get_total_sales() : 0;
}
}, 10, 2 );
add_filter( 'manage_edit-product_sortable_columns', function ( $columns ) {
$columns['wpide_sales'] = 'wpide_sales';
return $columns;
} );
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() && $query->is_main_query() && 'wpide_sales' === $query->get( 'orderby' ) ) {
$query->set( 'meta_key', 'total_sales' );
$query->set( 'orderby', 'meta_value_num' );
}
} );
Notes
Uses the total_sales counter WooCommerce keeps for each product.
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.