Jake W
Jake W

Reputation: 43

Display used coupons in a custom column in WooCommerce "My account" orders table

My intention is to display the coupons used in an order, in a custom column in the order table of WooCommerce "My Account".


Image of table on site:

table on site

My code attempt:

add_filter( 'woocommerce_account_orders_columns', 
'add_coupon_codes_column');
    function add_coupon_codes_column( $columns ){
        $new_columns = [
        "order-number" => $columns["order-number"],
        // ...
        "coupon-codes" => __( 'Code', '' ),
        // ...
        "order-actions" => $columns["order-actions"]
    ];
    return $new_columns;
}

add_action( 'woocommerce_my_account_my_orders_column_coupon_codes', 
'add_coupon_codes_content' );
    function add_coupon_codes_content($order) {
    echo esc_html($order->get_coupon_codes());
}

Which is based on Add a custom column with meta data to My Account Orders table in Woocommerce 3+ answer code.


I can create the column just fine, but unfortunately the desired data does not appear. Someone who can assist me with this?

Upvotes: 4

Views: 520

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29640

You are close with your code attempt, however there is no real need to iterate over the existing columns. Unless you like to determine the sequence from the new column.

Subsequently, for the output of the coupon codes, several options are available, one of which is for example using implode()

So you get:

// Add new column(s) to the "My Orders" table in the account.
function filter_woocommerce_account_orders_columns( $columns ) {
    $columns['coupon-codes'] = __( 'Coupons', 'woocommerce' );

    return $columns;
}
add_filter( 'woocommerce_account_orders_columns', 'filter_woocommerce_account_orders_columns', 10, 1 );

// Adds data to the custom column in "My Account > Orders"
function action_woocommerce_my_account_my_orders_column_coupon_codes( $order ) {
    // Get codes
    $coupon_codes = $order->get_coupon_codes();
        
    if ( ! empty( $coupon_codes ) ) {
        echo implode( ', ', $coupon_codes );
    }
}
add_action( 'woocommerce_my_account_my_orders_column_coupon-codes', 'action_woocommerce_my_account_my_orders_column_coupon_codes', 10, 1 );

Related: Add multiple custom columns to WooCommerce "My account" orders table

Upvotes: 2

Related Questions