Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WP - WOO | Add custom field to shop_order Woocommerce Admin Order's List #wordpress #woocommerce
<?php
/**
* Add a new Column to shop_order
* admin list Woocommerce and show custom fields
* Use in functions.php
*/
function add_new_column_orders_woo( $columns ) {
$new_columns = array();
foreach ( $columns as $column_name => $column_info ) {
$new_columns[ $column_name ] = $column_info;
if ( 'order_total' === $column_name ) {
// replace to customize
$new_columns['order_column_data'] = __( 'The title of the column', 'your-theme-text-domain' );
}
}
return $new_columns;
}
add_filter( 'manage_edit-shop_order_columns', 'add_new_column_orders_woo', 20 );
if ( ! function_exists( 'sv_helper_get_order_meta' ) ) :
/**
* Helper function to get meta for an order.
*
* @param \WC_Order $order the order object
* @param string $key the meta key
* @param bool $single whether to get the meta as a single item. Defaults to `true`
* @param string $context if 'view' then the value will be filtered
* @return mixed the order property
*/
function sv_helper_get_order_meta( $order, $key = '', $single = true, $context = 'edit' ) {
// WooCommerce > 3.0
if ( defined( 'WC_VERSION' ) && WC_VERSION && version_compare( WC_VERSION, '3.0', '>=' ) ) {
$value = $order->get_meta( $key, $single, $context );
} else {
// have the $order->get_id() check here just in case the WC_VERSION isn't defined correctly
$order_id = is_callable( array( $order, 'get_id' ) ) ? $order->get_id() : $order->id;
$value = get_post_meta( $order_id, $key, $single );
}
return $value;
}
endif;
/**
* Output Custom fields
*
* @param string[] $column name of column being displayed
*/
function add_order_column_data_content( $column ) {
global $post;
$order = wc_get_order( $post->ID );
// add fields replace your_field_name
$render_field = sv_helper_get_order_meta( $order, 'your_field_name' );
// echo custom fields
echo $render_field;
}
add_action( 'manage_shop_order_posts_custom_column', 'add_order_column_data_content' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment