Now Reading: Add product SKUs to your product URLs

Loading

Add product SKUs to your product URLs

svg09/25/2023Wordpressamirog

This code snippet empowers your WooCommerce store by seamlessly integrating product SKUs into your product page URLs. With this enhancement, your website’s product URLs will feature a user-friendly structure, improving both SEO and user navigation. Learn how to implement this customization to optimize your online shopping experience.

//add this code to function.php file , coded by amirog.com
function custom_woocommerce_permalink_structure($post_link, $post, $leavename, $sample)
{
    if (strpos($post_link, '%product_sku%') === false || !is_object($post))
        return $post_link;

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

    if (empty($product_sku))
        return $post_link;

    $post_name = sanitize_title($post->post_title);
    $post_link = str_replace('%product_sku%', $product_sku, $post_link);
    $post_link = str_replace('%postname%', $post_name, $post_link);

    return $post_link;
}

function custom_woocommerce_rewrite_rules($rules)
{
    $new_rules = array(
        'product/([^/]+)/([^/]+)/?$' => 'index.php?product=$matches[2]',
    );

    return $new_rules + $rules;
}

function add_custom_permalink_structure()
{
    add_rewrite_tag('%product_sku%', '([^&]+)');
    add_permastruct('product', 'product/%product_sku%/%postname%/');
}

add_action('init', 'add_custom_permalink_structure');
add_filter('post_type_link', 'custom_woocommerce_permalink_structure', 10, 4);
add_filter('rewrite_rules_array', 'custom_woocommerce_rewrite_rules');

After adding this code to your WordPress site, remember to flush your rewrite rules by visiting the “Settings” > “Permalinks” page in the WordPress admin area. This action ensures that the new permalink structure takes effect.

1 People voted this article. 1 Upvotes - 0 Downvotes.
svg

What do you think?

Show comments / Leave a comment

Leave a reply

Loading
svg
Quick Navigation
  • 01

    Add product SKUs to your product URLs