Emmanuel Kuebu
Emmanuel Kuebu

Reputation: 79

Add product SKU in WooCommerce "My account" orders table

Currently, this is the text on the woocommerce order table under the total column. (GHS 5.00 for 10 items)

Default total text


I want to display the SKU of the product from the order. So it should be GHS 5.00 for 10 SKU.

I have setup the site such that you cannot buy more that one product at a time.

New total text


I use this snippet that's able to change the text am I can't get the product SKU to show

add_filter('ngettext', 'remove_item_count_from_my_account_orders', 105, 3 );
function remove_item_count_from_my_account_orders( $translated, $text, $domain ) {
    switch ( $text ) {
        case '%1$s for %2$s item' :
            $translated = '%1$s';
            break;

        case '%1$s for %2$s items' :
            $translated = '%1$s';
            break;
    }
    return $translated;
}

Any advice?

Upvotes: 1

Views: 414

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29670

If you want to overwrite the text from the total column, but also want to add certain values ​​(such as the sku), you will have to overwrite the existing column.

This can be done via the woocommerce_my_account_my_orders_column_{$column_id} hook.

So you get:

// Overwrite the existing 'order-total' column
function filter_woocommerce_my_account_my_orders_column_order_total( $order ) {
    // Empty array
    $product_skus = array();

    // Loop through order items
    foreach( $order->get_items() as $item ) {
        // Get an instance of corresponding the WC_Product object
        $product = $item->get_product();
        
        // Get product SKU
        $product_sku = $product->get_sku();
    
        // NOT empty
        if ( ! empty ( $product_sku ) ) {
            // Push to array
            $product_skus[] = $product_sku;
        }
    }
    
    // Get item count
    $item_count = $order->get_item_count() - $order->get_item_count_refunded();
    
    // translators: 1: formatted order total 2: total order items
    echo wp_kses_post( sprintf( _n( '%1$s for %2$s ', '%1$s for %2$s ', $item_count, 'woocommerce' ) . implode( ", ", $product_skus ), $order->get_formatted_order_total(), $item_count ) );
}
add_action( 'woocommerce_my_account_my_orders_column_order-total', 'filter_woocommerce_my_account_my_orders_column_order_total', 10, 1 );

Upvotes: 1

Related Questions