/**
* Add new "Total Sales" column to the products list.
*/
add_filter( 'manage_edit-product_columns', 'wpcb_add_product_column_total_sales', PHP_INT_MAX );
function wpcb_add_product_column_total_sales( $columns ) {
$columns['total_sales'] = 'Total Sales';
return $columns;
}
/**
* Output "Total Sales" column.
*/
add_action( 'manage_product_posts_custom_column', 'wpcb_render_product_column_total_sales', PHP_INT_MAX );
function wpcb_render_product_column_total_sales( $column ) {
if ( 'total_sales' === $column ) {
$total_sales = get_post_meta( get_the_ID(), 'total_sales', true );
echo $total_sales;
}
}
/**
* This is only needed if you want to make the column sortable.
*/
add_filter( 'manage_edit-product_sortable_columns', 'wpcb_sortable_column_total_sales', PHP_INT_MAX );
function wpcb_sortable_column_total_sales( $columns ) {
$columns['total_sales'] = 'total_sales';
return $columns;
}
add_action( 'pre_get_posts', 'wpcb_sort_by_total_sales_column', PHP_INT_MAX );
function wpcb_sort_by_total_sales_column( $query ) {
if (
$query->is_main_query() &&
( $orderby = $query->get( 'orderby' ) ) && 'total_sales' === $orderby &&
isset( $query->query['post_type'] ) && 'product' === $query->query['post_type'] &&
isset( $query->is_admin ) && 1 == $query->is_admin
) {
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'total_sales' );
}
}
Nice snippet, I use it. Thank you for it.
But how to make this column sortable?
Hi,
Thanks.
I’ve just updated the snippet, so you can now set the column to be sortable.