Woocommerce Custom Product Slug

- 1 answer

Is there a way to create custom product URL based on the product attributes, I have a product sunglasses which has a couple of attributes tied to it: metal, blue and round, so the current URL is:

What I am trying to get is a URL which has those attributes included:

I would really appreciate if someone would even just point me to the right direction on how to tackle this.



There are two ways to do this, either Manually or Programmatically.

Manually adjusting permalinks:

In your example, you are simply adjusting the product URL to include attributes. This can be achieved manually by editing the permalink on the product itself.

Once the product has been added/saved, you will see the permalink showing directly under the title field like this:

enter image description here

Simply click the Edit button next to it and change it from abram-widana-629 to abram-widana-meta-blue-round-629

Programmatically adding attributes to permalinks:

If you want to try to achieve this permanently for all products you will have to work through the "save_post" filter/hook to add all the attributes to the permalink. The only downfall from this is that you will no longer be able to adjust your individual permalinks for your products as they will simply revert back once you click save.

Below is a code example of how to achieve that:

add_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );
function add_custom_attributes_to_permalink( $post_id, $post, $update ) {

    //make sure we are only working with Products
    if ($post->post_type != 'product' || $post->post_status == 'auto-draft') {

    //get the product
    $_product = wc_get_product($post_id);

    //get the "clean" permalink based on the post title
    $clean_permalink = sanitize_title( $post->post_title, $post_id );

    //next we get all of the attribute slugs, and separate them with a "-"
    $attribute_slugs = array(); //we will be added all the attribute slugs to this array
    foreach ($_product->get_attributes(); as $attribute_slug => $attribute_value) {
        $attribute_slugs[] = $attribute_value;
    $attribute_suffix = implode('-', $attribute_slugs);

    //then add the attributes to the clean permalink
    $full_permalink = $clean_permalink.$attribute_suffix;

    // unhook the save post action to avoid a broken loop
    remove_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );

    // update the post_name (which becomes the permalink)
    wp_update_post( array(
        'ID' => $post_id,
        'post_name' => $full_permalink

    // re-hook the save_post action
    add_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );