Alexandre Deplancke
Alexandre Deplancke

Reputation: 157

Replace product title by the SKU in Woocommerce single product page

I am using Woocommerce and on the Product pages I would like to display the SKU instead of the product title.

I've tried this code:

add_action( 'woocommerce_single_product_summary', 'custom_before_title' );
function custom_before_title() {

    global $product;

    if ( $product->get_sku() ) {
        echo $product->get_sku();
    }

}

but the SKU is displayed just after the price and this is not what I want. I would like at least that the SKU is displayed just after the product title. How can I do that?

Any help is appreciated.

Upvotes: 2

Views: 1428

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253919

The following code will replace the product title by the product SKU on single product pages:

add_action( 'woocommerce_single_product_summary', 'replace_product_title_by_product_sku', 4 );
function replace_product_title_by_product_sku() {
    global $product;

    if ( $product->get_sku() ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
        add_action( 'woocommerce_single_product_summary', 'display_product_sku_as_title', 5 );
    }
}

function display_product_sku_as_title() {
    global $product;

    echo '<h1 class="product_title entry-title">' . esc_html( $product->get_sku() ) . '</h1>';
}

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


To display the product SKU below the title you will use:

add_action( 'woocommerce_single_product_summary', 'display_product_sku_below_title', 6 );
function display_product_sku_below_title() {
    global $product;

    if ( $sku = $product->get_sku() ) {
        echo '<p class="product_sku">' . esc_html( $sku ) . '</p>';
    }
}

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

Upvotes: 1

Related Questions