John Davidson

php - How to show product name in a new column in WooCommerce "My account" orders table

0 comments
Message:


I have added a new column in recent order table. I want to show the product name in this column.


I am using below php code. Is it possible making some changes to this code to show the products name instead?


**
* Adds a new column to the "My Orders" table in the account.
*
* @param string[] $columns the columns in the orders table
* @return string[] updated columns
*/
function th_wc_add_my_account_orders_column( $columns ) {

$new_columns = array();

foreach ( $columns as $key => $name ) {

$new_columns[ $key ] = $name;

// add ship-to after order status column
if ( 'order-status' === $key ) {
$new_columns['new-data'] = __( 'New Data', 'textdomain' );
}
}

return $new_columns;
}
add_filter( 'woocommerce_my_account_my_orders_columns', 'th_wc_add_my_account_orders_column' );

/**
* Adds data to the custom "new-data" column in "My Account > Orders".
*
* @param \WC_Order $order the order object for the row
*/
function th_wc_my_orders_new_data_column( $order ) {

$new_data = get_post_meta( $order->get_id(), 'new_data', true ); // Get custom order meta
echo ! empty( $new_data ) ? $new_data : '–';

}
add_action( 'woocommerce_my_account_my_orders_column_new-data', 'th_wc_my_orders_new_data_column' );


My Answer:
To show the product name in the new column instead of the custom "new_data" meta, you can modify the code as follows:

php
/**
* Adds a new column to the "My Orders" table in the account.
*
* @param string[] $columns the columns in the orders table
* @return string[] updated columns
*/
function th_wc_add_my_account_orders_column( $columns ) {

$new_columns = array();

foreach ( $columns as $key => $name ) {

$new_columns[ $key ] = $name;

// add product name after order status column
if ( 'order-status' === $key ) {
$new_columns['product-name'] = __( 'Product Name', 'textdomain' );
}
}

return $new_columns;
}
add_filter( 'woocommerce_my_account_my_orders_columns', 'th_wc_add_my_account_orders_column' );

/**
* Adds data to the custom "product-name" column in "My Account > Orders".
*
* @param \WC_Order $order the order object for the row
*/
function th_wc_my_orders_product_name_column( $order ) {

$items = $order->get_items();

foreach ( $items as $item ) {
$product_name = $item->get_name();
echo $product_name . '
';
}

}
add_action( 'woocommerce_my_account_my_orders_column_product-name', 'th_wc_my_orders_product_name_column' );


This code will display the product names of all items in the order in the new "Product Name" column in the "My Account > Orders" table.

Rate this post

5 of 5 based on 9689 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us