We have a lot of returning customers so I'm trying to display user lifetime value (LTV - SUM of all past orders) on WooCommerce admin orders list to quickly identifiy best users.
But I don't even know if that is possible. I have a custom column to see if it's returning buyers or not, but don't have idea where to start for LTV.
My code for marking returned buyers:
add_filter( 'manage_shop_order_posts_columns',
'shalior_wc_set_custom_edit_post_columns',99,1 );
function shalior_wc_set_custom_edit_post_columns($columns) {
$columns['is-returning'] = __( 'Is returning?', 'your_text_domain' );
return $columns;
}
add_action( 'manage_shop_order_posts_custom_column' , 'shalior_wc_is_returning', 99, 2 );
function shalior_wc_is_returning( $column, $post_id ) {
switch ( $column ) {
case 'is-returning':
$order = new WC_Order( $post_id );
$user_id = $order->get_user_id();
$orders_count = wc_get_customer_order_count( $user_id );
echo $orders_count > 1 ? '<span style="color: #040404; background: #9ae288;
padding: 3px; padding-left: 12px; padding-right: 12px; border-radius: 3px;">Yes</span>' : "No" ;
break;
}
}
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
echo '<style>
td.is-returning.column-is-returning {
text-align: center;
}
th#is-returning {
text-align: center;
}
th.manage-column.column-is-returning {
text-align: center;
}
td.order_coupons.column-order_coupons {
text-align: center;
}
th#order_coupons {
text-align: center;
}
th.manage-column.column-order_coupons {
text-align: center;
}
</style>';
}
You can use the get_total_spent()
function, which return how much money a customer has spent
So you get:
/**
* Add column
*/
function filter_manage_edit_shop_order_columns( $columns ) {
$columns['total-spent'] = __( 'LTV', 'woocommerce' );
return $columns;
}
add_filter( 'manage_edit-shop_order_columns', 'filter_manage_edit_shop_order_columns', 10, 1 );
/**
* Populate column
*/
function filter_manage_shop_order_posts_custom_column( $column, $post_id ) {
// Compare
if ( $column == 'total-spent' ) {
// Get order
$order = wc_get_order( $post_id );
// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
// Get user id
$user_id = $order->get_user_id();
// NOT empty
if ( ! empty ( $user_id ) ) {
// Get customer
$customer = new WC_Customer( $user_id );
// Output
echo $customer->get_total_spent();
} else {
// Output
echo __( 'N/A', 'woocommerce' );
}
}
}
}
add_filter( 'manage_shop_order_posts_custom_column', 'filter_manage_shop_order_posts_custom_column', 10, 2 );