1
votes

Using Woocommerce, I would like to add the SKU instead of the product title in the following pages: Shop page, Cart page and Checkout page.

For example in shop page, I am able to add the SKU above the product title using the code below. However, the problem is that the SKU added doesn't have the link to the single product page.

add_action( 'woocommerce_shop_loop_item_title', 'sku_before_title', 9 );
function sku_before_title()  {

    global $product;

    $sku = $product->get_sku();
    echo '<p class="name product-title">Product ' . $sku . '</p>';
}

What is the correct code to have SKU instead of product title and keeping the same link and CSS as the product title? Code for Shop page and Cart page and Checkout page.

1

1 Answers

1
votes

To replace the product title by the sku on WooCommerce archive pages you will use:

// Frontend: On shop and archives pages
add_action( 'woocommerce_shop_loop_item_title', 'sku_replace_title_on_loop', 9 );
function sku_replace_title_on_loop()  {
    global $product;

    // Remove the product title
    remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );

    $sku = $product->get_sku();

    // Replace the title by the Sku if is not empty
    $title = empty($sku) ? get_the_title() : $sku;

    // Output
    echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . $title . '</h2>';
}

For cart and checkout pages, you will use:

// Frontend: on cart, minicart and checkout
add_filter( 'woocommerce_cart_item_name', 'sku_replace_title_on_cart_checkout', 10, 3 );
function sku_replace_title_on_cart_checkout( $item_name, $cart_item, $cart_item_key ) {
    if( $sku = $cart_item['data']->get_sku() ) {
        if( is_cart() ) {
            $item_name = sprintf( '<a href="%s">%s</a>', esc_url( $cart_item['data']->get_permalink( $cart_item ) ), $sku );
        } else {
            $item_name = $sku;
        }
    }
    return $item_name;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.