Last active
April 25, 2019 16:13
-
-
Save amouratoglou/63e21669c80c95ef2f670b5f8b7b64ea to your computer and use it in GitHub Desktop.
WP - WOO | Add custom field to shop_order Woocommerce Admin Order's List #wordpress #woocommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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