I want the field for user roles (customer, foretag_1) to have different background colors to make them more easily distinguishable. See the image attached.
Here’s the PHP code used to add field for user role in WooCommerce admin order list :
add_filter('manage_edit-shop_order_columns', 'add_column_heading', 20, 1);
function add_column_heading($array) {
$res = array_slice($array, 0, 2, true) +
array("customer_role" => "Customer Role") +
array_slice($array, 2, count($array) - 1, true);
return $res;
}
add_action('manage_posts_custom_column', 'add_column_data', 20, 2);
function add_column_data($column_key, $order_id) {
// exit early if this is not the column we want
if ('customer_role' != $column_key) {
return;
}
$customer = new WC_Order( $order_id );
if($customer->user_id != ''){
$user = new WP_User( $customer->user_id );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role )
echo $role;
}
}
}
I haven’t tried anything yet due to insufficient knowledge of how to achieve background colors based on user roles.
I have read the following threads but lack the know-how to adjust and implement the solutions for my specific needs:
2
Answers
As you do, this hook adds a new column:
Adds an HTML div element to the inserted custom cell:
Example HTML output of a cell:
PHP code that adds CSS styling to the WooCommerce order listing page only:
Here, the
padding
value of thetd
element, which is1em
, is set to0
. We apply1em
padding
to thediv
element we added manually. This way the background color covers the entire cell. Add any other user role values you want to the CSS rules.Result:
Tested on WordPress 6.5.2 – WooCommerce 8.8.3
There are some mistakes and missing things in your code.
The following code will handle Legacy Orders and High-Performance Order Storage (HPOS), displaying a custom column with your user roles colored just as order status do:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
You will get something like:
You can easily adjust the desired background color for each user role.