Let’s say your WooCommerce product has the following permalink: example.com/shop/t-shirts-tops-and-blouses/t-shirt-casual-v-neck-longsleeve-green-medium-cotton-stretch
Wouldn’t it be shorter, more fun and neater if you could also reach the same exact single product page by using example.com/sku00001
in the browser bar, where “sku00001” is the product SKU?
Well, in today’s snippet we will create a simple redirect from a custom URL that contains the product SKU to the product page, so that you can use the URL “shortener“ in your email marketing, display advertising, blog posts and anywhere you want to show a “pretty link” instead of a full, long, boring product page URL.
Enjoy!
PHP Snippet: Redirect “example.com/sku” To The WooCommerce Single Product Page
/**
* @snippet Redirect SKU in URL to Woo Product Page
* @tutorial Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 8
* @community Join https://businessbloomer.com/club/
*/
add_action( 'template_redirect', 'bbloomer_redirect_sku_in_url_to_product' );
function bbloomer_redirect_sku_in_url_to_product() {
if ( is_404() && ( $sku = $GLOBALS['wp']->request ) && ( $id = wc_get_product_id_by_sku( $sku ) ) ) {
wp_redirect( get_permalink( $id ) );
exit;
}
}
- The first line hooks the function
bbloomer_redirect_sku_in_url_to_product
to thetemplate_redirect
action. This means the function will be called whenever a WordPress template is redirected, which is typically on every page load. - The
bbloomer_redirect_sku_in_url_to_product
function itself is commented to explain its purpose, which is to redirect URLs containing a Stock Keeping Unit (SKU) to the corresponding product page. - Inside the function, we first check if the current page is a 404 error page using the
is_404()
function. This is because we only want to redirect URLs that result in a 404 error, which might be the case if someone types in a product SKU directly in the browser address bar. - If it is a 404 page, we then try to retrieve the request string from the global
$wp
object. - We then use the WooCommerce function
wc_get_product_id_by_sku($sku)
to try to get the product ID for the SKU in the request string. - If a product ID is found for the SKU, we use the WordPress function
wp_redirect(get_permalink($id))
to redirect the user to the product’s permalink. Theget_permalink($id)
function retrieves the permanent URL for the product with the given ID. - Finally, we use the
exit
function to stop the function from executing any further code after the redirect.
Once I disabled the media pages (which were blocking the required slugs, due to the product images being named after the SKUs, using this helpful little plugin: “disable-media-pages”), the code above worked like a charm!
Thanks a ton for sharing! 🙂
Awesome