How to add sku to product url in Woocommerce?

In this tutorial we’ll learn how to add product sku to product url in woocommerce.

By default when you go to a product page you’ll notice this kind of url:

Our team at Themelocation is comprised of WordPress developers of high expertise

  • We can maintain, support and manage your single, or all your clients, website with dedication
  • Our skills are at your disposal.

Book a Call

Now let’s say I want to add product sku to their corresponding url.

To do this add the following lines of code at the end of functions.php file of your theme.

function jpb_custom_meta_permalink( $link, $post ){

$post_meta = get_post_meta( $post->ID, '<insert your meta key here>', true );

if( empty( $post_meta ) || !is_string( $post_meta ) )

   $post_meta = '<insert your default value (could be an empty string) here>';

$link = str_replace( '!!custom_field_placeholder!!', $post_meta, $link );

return $link;

}

 

add_filter( 'post_link', 'jpb_custom_meta_permalink', 10, 2 );

 

function append_sku_string( $link, $post ) {

$post_meta = get_post_meta( $post->ID, '_sku', true );

     if ( 'product' == get_post_type( $post ) ) {

       $link = $link . '#' .$post_meta;

       return $link;

     }

}

add_filter( 'post_type_link', 'append_sku_string', 1, 2 );

You can access functions.php file here:

Woocommerce

Place the code and save file.

Now when I go to a product page, by clicking on the product from archive page i.e category and shop page, product specific sku will be added to url.

Woocommerce

However, If you want to add SKU post meta in permalink Like: http://www.domain.tld/shop/SKU/productname then use the following method.

Sorted it issue with a RewriteRule in .htaccess! Has to be placed above the RewriteCond lines of the htaccess code generated by WordPress, so to make it more fool proof I just added it outside and in front of the WordPress generated code:

    # BEGIN WC SKU post meta in permalink (note: requires code in functions.php as well)

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase / 

    RewriteRule ^whisky/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ ?sku=$1&product=$2 [NC,L]
    </IfModule>

    # END WC SKU post meta in permalink  

     

    # BEGIN WordPress

    ...

Seems to work seamlessly so far.

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *