The idea here is that WooCommerce creates a custom meta field total_sales for each product and stores the number of total sales in it. It allows us to use this value inside pre_get_posts hook and create a sortable column!

Here is the result what we are going to create:

And here is the code for your functions.php:

// add
add_filter( 'manage_edit-product_columns', 'rudr_add_product_list_column' );
function rudr_add_product_list_column( $column_name ) {

	// a little different way of adding new columns
	return wp_parse_args(
		array(
			'total_sales' => 'Total Sales'
		),
		$column_name
	);

}

// populate
add_action( 'manage_posts_custom_column', 'rudr_populate_product_column', 25, 2 );
function rudr_populate_product_column( $column_name, $product_id ) {

	if( 'total_sales' === $column_name ) {
		echo get_post_meta( $product_id, 'total_sales', true );
	}

}

// make sortable
add_filter( 'manage_edit-product_sortable_columns', 'rudr_sortable_column' );
function rudr_sortable_column( $sortable_columns ) {

	return wp_parse_args(
		array(
			'total_sales' => 'by_total_sales' // column name => sortable arg
		),
		$sortable_columns
	);

}

// doing to sorting stuff
add_action( 'pre_get_posts', function( $query ) {

	if( ! is_admin() || empty( $_GET[ 'orderby' ] ) || empty( $_GET[ 'order' ] ) ) {
		return $query;
	}

	if( 'by_total_sales' === $_GET[ 'orderby' ] ) {
		$query->set( 'meta_key', 'total_sales' );
		$query->set( 'orderby', 'meta_value_num' );
		$query->set( 'order', $_GET[ 'order' ] );
	}

	return $query;

} );

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.