Nicola Mustone

Happiness Lead @ Automattic



Make Product Attributes Linkable

Update November 21st, 2023: I’ve tested this script with WooCommerce 8.3.0, and it’s fully functional.

In the dynamic world of e-commerce, product attributes in WooCommerce play a pivotal role. By transforming these attributes into clickable links, we open doors to a more intuitive and informative shopping experience.

Understanding Product Attributes in WooCommerce

Product attributes are the backbone of product differentiation in WooCommerce. They can be global, used across multiple products, or local, specific to individual products. Understanding this distinction is key to effective product management. You can learn more about them in the WooCommerce documentation, but here is a quick guide:

You can create Global attributes from Products > Attributes, they are taxonomies, like product categories or post tags. Any product can use an attribute defined there, this is why they are global.

You can instead define Local attributes in the product, while creating/editing it, in the tab Attributes. They are available only on the product where they have been defined and not usable by other products.

The Advantages of Linkable Product Attributes

Making attributes linkable can significantly enhance your store’s usability and SEO. It allows customers to easily navigate and find products based on specific attributes, creating a more engaging user journey.

Making Product Attributes Linkable

Tailoring your WooCommerce store to include linkable attributes involves custom coding. This approach offers unparalleled flexibility, allowing you to create a unique and user-friendly shopping environment.

Because of the difference between the two types of attributes that we outlined earlier, we need to use two different ways to add a URL to the product attribute term.

Before implementing any code changes, always ensure your site is backed up. This will help you restore things in case of unforeseen errors. I recommend using Jetpack Backup for real-time backups and one-click restores.

Open your functions.php file in wp-content/themes/your-child-theme-name/ and add this code at the end of the file:

<?php
/**
* Register term fields for WooCommerce attributes.
*/
add_action( 'init', 'register_attributes_url_meta' );
function register_attributes_url_meta() {
$attributes = wc_get_attribute_taxonomies();
foreach ( $attributes as $tax ) {
$name = wc_attribute_taxonomy_name( $tax->attribute_name );
add_action( "{$name}_add_form_fields", 'add_attribute_url_meta_field' );
add_action( "{$name}_edit_form_fields", 'edit_attribute_url_meta_field', 10 );
add_action( "edited_{$name}", 'save_attribute_url' );
add_action( "create_{$name}", 'save_attribute_url' );
}
}
/**
* Add URL field to the new attribute term form.
*/
function add_attribute_url_meta_field() {
wp_nonce_field( basename( __FILE__ ), 'attribute_url_meta_nonce' );
?>
<div class="form-field">
<label for="attribute_url"><?php esc_html_e( 'URL', 'woocommerce' ); ?></label>
<input type="url" name="attribute_url" id="attribute_url" value="" />
</div>
<?php
}
/**
* Add URL field to the edit attribute term form.
*/
function edit_attribute_url_meta_field( $term ) {
$url = get_term_meta( $term->term_id, 'attribute_url', true );
wp_nonce_field( basename( __FILE__ ), 'attribute_url_meta_nonce' );
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="attribute_url"><?php esc_html_e( 'URL', 'woocommerce' ); ?></label></th>
<td>
<input type="url" name="attribute_url" id="attribute_url" value="<?php echo esc_url( $url ); ?>" />
</td>
</tr>
<?php
}
/**
* Save URL field for attribute terms.
*/
function save_attribute_url( $term_id ) {
if ( ! isset( $_POST['attribute_url'], $_POST['attribute_url_meta_nonce'] ) ||
! wp_verify_nonce( $_POST['attribute_url_meta_nonce'], basename( __FILE__ ) ) ) {
return;
}
$new_url = esc_url_raw( $_POST['attribute_url'] );
update_term_meta( $term_id, 'attribute_url', $new_url );
}
/**
* Filter to make product attributes linkable.
*/
add_filter( 'woocommerce_attribute', 'make_product_atts_linkable', 10, 3 );
function make_product_atts_linkable( $text, $attribute, $values ) {
$new_values = array();
foreach ( $values as $value ) {
if ( $attribute['is_taxonomy'] ) {
// Handle global attributes
$term = get_term_by( 'name', $value, $attribute['name'] );
if ( ! is_wp_error( $term ) && ! empty( $term ) ) {
$url = get_term_meta( $term->term_id, 'attribute_url', true );
if ( ! empty( $url ) ) {
$new_values[] = '<a href="' . esc_url( $url ) . '" title="' . esc_attr( $value ) . '">' . esc_html( $value ) . '</a>';
} else {
$new_values[] = esc_html( $value );
}
}
} else {
// Handle local attributes (Markdown syntax)
if ( preg_match( "/\[(.*?)\]\((.*?)\)/", $value, $matches ) ) {
$link_text = esc_html( $matches[1] );
$link_url = strip_tags( $matches[2] ); // Directly use the URL from the match
// Continue with your existing logic
if ( filter_var( $link_url, FILTER_VALIDATE_URL ) ) {
$new_values[] = '<a href="' . esc_url( $link_url ) . '">' . $link_text . '</a>';
} else {
// If the URL isn't valid, just use the text
$new_values[] = $link_text;
}
}
}
}
return implode( ', ', $new_values );
}
view raw functions.php hosted with ❤ by GitHub

From line 2 to line 68, the code adds a field named URL in the form for creating and editing global attributes. The functions are to register the field, add it in the Add New term form, add it in the Edit term form and save the field.

From line 70 to the end of the file, it tweaks the values in the tab Additional Information in the single product page to handle the URL of the product attribute term. This function, also handles URLs for local attributes.

How to Use The Product Attribute URL

For global attributes, go to Products > Attributes and add a new attribute, or edit an existing one. It will appear in the table on the right. Click on the cogs icon to add product attribute terms in it, you will see this form:

The Add new Color form shows the Name, Slug and Description text fields, followed by a new URL field added by the snippet from this article.

As you can see, there’s a new field at the bottom of the form Add new Color (Color is the name of the attribute I used for this example), named URL. Write there the URL you want the product attribute term to link to.

The same field is available while editing the product attribute term:

The image shows the Edit Attribute Term form for a term called Color, showing the new custom URL field.

For local attributes instead, we don’t have an interface like this, so we have to find a workaround to add URLs to product attribute terms.

Do not use this method for local attributes that are Used for Variations. The script is not meant to handle such cases. Use it only for attributes that are shown on the product page but not used for variations.

Did you know that I love Markdown? That is what we are going to use for local attributes, Markdown!

Edit a product from Products > All Products and open the Attributes tab. From here, add a new Custom product attribute. Then give it a name and add some values using Markdown to create links:

[Text shown](https://myurl.com)

This is the format to use. An example is shown in this screenshot:

The attributes form in WooCommerce showing the markdown value of an attribute

The second attribute here, Test, is the local attribute.

Now click on Save Attributes and Publish your product. This is how it will appear on the website:

The Additional Information tab on WooCommerce showing the local and global attributes as links.

Enhancing Your Store with Linkable Attributes

Linkable product attributes not only enhance the functionality of your WooCommerce store but also enrich the customer experience. They are a testament to the flexibility and adaptability of WooCommerce as an e-commerce platform.

Have you tried making your product attributes linkable? Share your experiences and tips in the comments below.

Advertisements

Subscribe to This Blog

Receive new articles from this blog directly in your inbox! No spam guaranteed!

Join 651 other subscribers

Contribute to Improving This Blog

Did you enjoy this article? Was it helpful? Contribute to help me write more articles! The funds collected from this blog are reinvested directly into improving my skills or the blog so that I can provide more and better content!

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

€5.00
€15.00
€100.00
€5.00
€15.00
€100.00
€5.00
€15.00
€100.00

Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly
Advertisements

More Posts That You Might Like…


62 responses to “Make Product Attributes Linkable”

  1. THANK YOU!!! it works!! <3

    1. You’re welcome Luca!

  2. I was able to add this code and it worked. My problem is I am trying to import the data into the woocommerce products via the WPallImport plugin. So far, this isn’t working so I was wondering if you had another suggestion for importing the data from a csv file so that the attributes have the url link….

    1. Hi Todd,
      I’m sorry but I don’t know why it is not working. From a first look it should work, WP All Import support may be able to help you more about it.

  3. I’m using the plugin WooCommerce Show Attributes to move product attributes into the Short Description area. However, the custom links from your code no longer works when that plugin is active. Any tweaks to the code to still make the custom links work? Thanks!

    1. Hi Jon,
      I checked the plugin you are using, but unfortunately it does not have any filter that we can use to parse the Markdown and get my snippet to work also with that code.

      If you are able to contact the plugin author and ask them to add some filters, then I’d be able to make it work.

  4. That is a really well thought out post! Does exactly what I was looking for. Many thanks Nicola!

    1. You are welcome Nick!

  5. Thank you very much for your post! My situation is a bit different and probably a lot simpler (at least I hope it is), but I just can’t figure out how to resolve it. I hope you can help.

    I want to be able to click on phrase “Select Amount” at the top of my client’s Shop page (http://soul2soulhealer.wsbydesign.com/shop) and have it take the visitor to the bottom of the description so he/she can access the Select Amount button without having to scroll down the page. I’ve become painfully aware that anchors don’t work, and perhaps I need all the code you’ve shared, but I’m hoping it’s something a bit less involved since I’m slowing but surely making my way outside my comfort zone as a designer.

    Any feedback you can provide is greatly appreciated! Thank you in advance!

  6. Hi!
    Thank you for the snippet. Work great.
    But I get Fatal error when woocommerce update.

    Fatal error: Uncaught Error: Call to undefined function wc_get_attribute_taxonomies() in /Volumes/data/web_dev/local_sites/mysite.com/wp-content/themes/Impreza-child/functions.php:94 Stack trace: #0 /Volumes/data/web_dev/local_sites/mysite.com/wp-includes/class-wp-hook.php(298): register_attributes_url_meta('') #1 /Volumes/data/web_dev/local_sites/mysite.com/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters(Object(Nova_Restaurant), Array) #2 /Volumes/data/web_dev/local_sites/mysite.com/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #3 /Volumes/data/web_dev/local_sites/mysite.com/wp-settings.php(449): do_action('init') #4 /Volumes/data/web_dev/local_sites/mysite.com/wp-config.php(95): require_once('/Volumes/data/w...') #5 /Volumes/data/web_dev/local_sites/mysite.com/wp-load.php(37): require_once('/Volumes/data/w...') #6 /Volumes/data/web_dev/local_sites/mysite.com/wp-admin/admin.php(31): require_once('/Volumes/data/w...') #7 /Volumes/data/web_dev/local_sites/mysite.com/wp-admin/update.php in /Volumes/data/web_dev/local_sites/mysite.com/wp-content/themes/Impreza-child/functions.php on line 94

    Line 94 in my functions.php is the third line of your snippet:
    $attributes = wc_get_attribute_taxonomies();

    Please help me resolve this problem

  7. It would be useful adding a targeting option, too, to open target links in a new window.

    1. Hi Lorenzo,
      It can be done with global attributes by adding a new option.

      For local attributes it’s not that easy since technically Markdown does not support a targetfor links.

      I prefer to stick to the regular Markdown, but you should be able to achieve that by changing the regular expression in the code above to search for a target too.

  8. Hi Nicola, I would like to be able to use the link on the orders details screen in wooCommerce . If I add it locally it does appear on the order screen with the item but it will not link to the desired website. I only get the woo drop down screen asking to change product levels. Any ideas? Thanks

    1. Hey Josh,
      I’m not sure to understand what’s happening. Can you please try to explain that again?

      Maybe a screenshot would help!

  9. Nicola, this is an amazing script and I thank you for the hard work that went into it. As someone else asked, I made the modifications to have the URL opened in a blank page. It’s posted here, somewhat crudely in a comment, but I hope it will be useful!

    https://pastebin.com/bA53MtiC

  10. Hey, thanks for great post. Did you know, that you can improve your attributes even if you are not a programmer? This service https://www.popoverify.com allows you to add context-sensitive help through an WordPress plugin and even add a link or pictures to to your attributes and other WordPress content.

  11. Hi – Thanks for this post, it is what I was looking for. I just upgraded to WooCommerce 3.0.0 and now the code for managing Global product attributes does not work?

    I can still add and edit URL’s when editing the attribute, however, when the attribute displays on a product the URL link is not applied to the term being displayed.

    I think that the Woov3.0.0 must have changed something? I am happy to help troubleshoot and test.

  12. Hi I got this code working on additional info tab but what I need is how can I use it to display on the custom tab I just made.

    Any ideas?

    Thanks

    1. Hey,
      Sorry but I’m not sure what you are trying to do exactly. Can you explain?

  13. Hi!

    I have a question about your link, it works perfectly except i would like to have that link opens in a new tab on current browser? Is there a way to code that?

    1. Hi Teemu,
      It’s possible. In the snippet, replace <a href=" with <a target="_blank" href=".

  14. Hi,
    after adding the code into the child theme, I see the new box into attribute to add the URL.
    However, when I move the dropdown on the product, nothing is redirected.

    Does it work with variation product too?
    normally if we change the variation from the dropdown on the product page, the selection must have to redirect to the URL link to the attribute, right?

    Many thanks in advance
    Best

  15. What about the opposite? Some of my attributes are linkable, some are not. Is it possible to make them all not clickable, just the regular text?

  16. Was working great up until the latest woocommerce update. Had to remove the code because it caused the site to crash.

  17. Francesco Antonio Santangelo Avatar
    Francesco Antonio Santangelo

    Grande Nick, era proprio quello che mi serviva!

    1. Ciao Fra!
      Ottimo! 🙂

  18. Hello,
    thx for sharing. I can confirm that this code is working perfectly with Blaszok theme 3.9.6, WooCommerce 3.4.2. I use it in combination with product filter plugin and it does exactly what I needed. Thanks again.
    Enjoy summer
    dUDLAJ

    1. Hello!
      Thanks for confirming this!

      Have a great summer you too!

  19. Fantastic!

    Tested this and confirming it’s working great!

  20. Thanks, Nicola!

    1. You’re welcome!

  21. Hi Nicola,

    I tried your code on WooCommerce v3.4.4 and I have an issue with the markdown, it links directly to the product page itself instead of linking to the URL I put in the custom attribute.

    Maybe they changed something in the latest vesion of WooCommerce?

    Any help is appreciated, thank you!

  22. Hi Nicola,

    yes, same here. Code doesn’t work properly since any WP Update.
    Link leads to the product page itself.
    But when remove “http://” or “https://” in the URL it works as it did before.
    But that’s not “the best workaround”.
    Maybe you have a solution…

    Thanks a lot.
    Koepi

  23. Mohammad Goodarzi Avatar
    Mohammad Goodarzi

    Hi Nicola

    Thank you so much! It works for me <3

    I have a question. I don’t want to put a custom link for each attribute term. Instead, I want to it generate links automatically and when I click on that link be able to see all products that contain that attribute term. How is it possible?

  24. Is it possible for your splendid snippet is not working on explorer although everything is perfect for chrome?

    1. Depending on the version of Explorer that you are using, yes it is possible. I never tested it there.

      1. Any opinion for the solution?

        1. This silence seems as “no”?

  25. Thanks for the snippet. Works fantastic!

    How would I modify it it to support relative URLs? Relative URLs wont validate when I try to add/update the attrib term :/

    Thanks!

    1. Nevermind. I Figured it out. Just has to change the input type to text instead of url. Duh.

  26. Hello Nicola, your code is great and very helpful.

    Is it possible when clicking to the attribute swatch to change to another product page?

    (I have the same swatches for 4 products, and I made 4 listings changing only the color).

    It would be a great help!

  27. Hey there. It is a perfect article. But I’d like to use external link. Is this possible?

    Oliver

  28. i have copy pasted the code in the function.php the attribute shows the url filed but the link is directed to product page attribute

  29. i have copy pasted the code in the function.php the attribute shows the url filed but the link is directed to product page attribute – the code is not properly working

    1. tomasz bugajski Avatar

      delete https:// or http:// in url with markdown [text] (url)

  30. I have the same problem…

  31. code is not working for me . The attribute url redirct to product attribute page but i wnat it rediect to another product page please help.

  32. I added this code to the theme’s functions.php but when I clicked Products > Attributes it gave me this error “HTTP ERROR 500”, so I deleted the code but I’m still receiving the error. Please advise as I need to be able to access this part of the website.

    Kind Regards.

  33. Any updates on this? As it isn’t currently working. 🙂

  34. Hello, thanks for the info.

    Couid you please let us know how to make the link No-follow and open in a different tab.

    Thanks.

    1. Hello,
      You can edit line 91 to add the nofollow and target directly into all links.

      Changing it individually would require much more work since you’d have to edit the regular expression that parses the Markdown.

  35. Thank you very much for sharing this, it’s working really great!

  36. Great to see that the code is functioning after all the updates to Woocommerce.

    I’m trying to replace the entire text of one of my products Custom Product Attribute’s and the text contains a link to the Contact web page. How can this be done please?

    Many thanks for your excellent article.

  37. improveitsolutions Avatar
    improveitsolutions

    This is an absolutely incredible feature that you have provided!

    Is there any way to open the links in a new window?

  38. improveitsolutions Avatar
    improveitsolutions

    I get this notice for the above suggested code:
    [11-Feb-2022 14:56:41 UTC] PHP Notice: Trying to get property ‘term_id’ of non-object in /customers/3/4/9/bernerbecker.com/httpd.www/community/wp-content/themes/themify-ultra-child/functions.php on line 152

    The line holds this: $url = get_term_meta( $term->term_id, ‘attribute_url’, true );

    And is in your example line 79.

    I’m not sure, but something is causing attributes to disappear when saving the post. Maybe it could be the cause. Why does this happen and is there any easy way to solve this?

    Thanks!

  39. […] I would like to add a local product attribute value that will have a link which points to a particular ‘href’ value. I followed this blog and tried to add via the markup option mentioned at the end of the blog, the value turns into an anchor tag link but the href value is not taken properly. https://nicolamustone.blog/2016/03/11/make-product-attributes-linkable/ […]

  40. Can you show me how to add link to product attribute label, please ?

  41. Awesome! This code still works perfectly here in 2023 on WC v7.7.0. Just added & configured our custom product attribute URLs for https://www.drivencoffee.com/ — must better for customer navigation from product to product. Cheers!

  42. TALPOS ANDREI Avatar

    Thank u, works!

  43. Hi,

    I guess the Code in this article is writing to the database.

    A better solution would be to generate the attribut links, when a product page is opened.
    AND
    Only for those attributes that make sense to be clickable.

    With the following code sample and a proper configuration of the search extention Relevanssi or any other search extention, the clickable link will take the clicked term and redirect to the search page with the products listed that share the same search term.

    Use this code in a child-theme functions.php OR the plugin Code Snipped.
    I recommend Code Snipped.

    /**
    * Make specific custom attributes clickable links and ignore non-alphabetic words in German.
    */
    function make_specific_attributes_links( $attribute_html, $attribute, $values ) {
    $specific_attributes = array(
    ‘Kultivar-Model’,
    ‘Japanisches Wort’
    );

    // Check if it’s a custom attribute (not a global attribute) and is in the specific attributes list
    if ( ! $attribute[‘is_taxonomy’] && in_array( $attribute[‘name’], $specific_attributes ) ) {
    $attribute_values = array();

    foreach ( $values as $value ) {
    // Check if the value contains only alphabetic characters (German)
    if ( preg_match( ‘/^[a-zA-ZäöüÄÖÜß]+$/’, $value ) ) {
    // Create the search URL
    $search_url = home_url( ‘/?s=’ . urlencode( $value ) . ‘&post_type=product’ );

    // Generate the clickable link
    $attribute_link = ‘‘ . esc_html( $value ) . ‘‘;

    // Add the clickable link to the array of attribute values
    $attribute_values[] = $attribute_link;
    } else {
    // Non-alphabetic value, add it as plain text
    $attribute_values[] = esc_html( $value );
    }
    }

    // Implode the attribute values with the original separators
    $attribute_html = ” . implode( ‘, ‘, $attribute_values ) . ”;
    }

    return $attribute_html;
    }
    add_filter( ‘woocommerce_attribute’, ‘make_specific_attributes_links’, 10, 3 );

Leave a Reply

Advertisements

Categories

Newsletter

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Join 651 other subscribers

About The Author

Hi, I’m Nico! Support Lead at Automattic, championing WordPress.com & WooCommerce. Off-duty, I’m at Elemental Beacon, leading epic D&D adventures. Let’s connect, whether it’s about WordPress or a quest!

Advertisements

Don't Miss a Thing!

Receive new articles from this blog directly in your inbox!

No spam guaranteed!

Join 651 other subscribers

Continue Reading

%d bloggers like this: