Make product attributes linkable
I’ve been asked many times how to do make product attributes linkable, and yesterday I found a post in the WooCommerce support forum on WordPress.org about this as well, and I decided to write this article.
So, by default WooCommerce strips all the HTML from attributes values, this means that you can’t use an HTML anchor to make product attributes linkable. We can still do it though with some custom code.
Luckily, WordPress helps us now with term metas introduced in WordPress 4.4.
Add URLs to Your Product Attributes
In WooCommerce we have two types of product attributes:
- Global product attributes
- Local product attributes
What is the difference?
Global product attributes are created 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.
Local product attributes instead are defined 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.
Because of this difference, we need to use two different ways to add a URL to the product attribute term.
Open your functions.php file in wp-content/themes/your-child-theme-name/ and add this code at the end of the file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Register term fields | |
*/ | |
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( 'edit_' . $name, 'save_attribute_url' ); | |
add_action( 'create_' . $name, 'save_attribute_url' ); | |
} | |
} | |
/** | |
* Add term fields form | |
*/ | |
function add_attribute_url_meta_field() { | |
wp_nonce_field( basename( __FILE__ ), 'attrbute_url_meta_nonce' ); | |
?> | |
<div class="form-field"> | |
<label for="attribute_url"><?php _e( 'URL', 'domain' ); ?></label> | |
<input type="url" name="attribute_url" id="attribute_url" value="" /> | |
</div> | |
<?php | |
} | |
/** | |
* Edit term fields form | |
*/ | |
function edit_attribute_url_meta_field( $term ) { | |
$url = get_term_meta( $term->term_id, 'attribute_url', true ); | |
wp_nonce_field( basename( __FILE__ ), 'attrbute_url_meta_nonce' ); | |
?> | |
<tr class="form-field"> | |
<th scope="row" valign="top"><label for="attribute_url"><?php _e( 'URL', 'domain' ); ?></label></th> | |
<td> | |
<input type="url" name="attribute_url" id="attribute_url" value="<?php echo esc_url( $url ); ?>" /> | |
</td> | |
</tr> | |
<?php | |
} | |
/** | |
* Save term fields | |
*/ | |
function save_attribute_url( $term_id ) { | |
if ( ! isset( $_POST['attribute_url'] ) || ! wp_verify_nonce( $_POST['attrbute_url_meta_nonce'], basename( __FILE__ ) ) ) { | |
return; | |
} | |
$old_url = get_term_meta( $term_id, 'attribute_url', true ); | |
$new_url = esc_url( $_POST['attribute_url'] ); | |
if ( ! empty( $old_url ) && $new_url === '' ) { | |
delete_term_meta( $term_id, 'attribute_url' ); | |
} else if ( $old_url !== $new_url ) { | |
update_term_meta( $term_id, 'attribute_url', $new_url, $old_url ); | |
} | |
} | |
/** | |
* Show term URL | |
*/ | |
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'] ) { | |
$term = get_term_by( 'name', $value, $attribute['name'] ); | |
$url = get_term_meta( $term->term_id, 'attribute_url', true ); | |
if ( ! empty( $url ) ) { | |
$val = '<a href="' . esc_url( $url ) . '" title="' . esc_attr( $value ) . '">' . $value . '</a>'; | |
array_push( $new_values, $val ); | |
} else { | |
array_push( $new_values, $value ); | |
} | |
} else { | |
$matched = preg_match_all( "/\[([^\]]+)\]\(([^)]+)\)/", $value, $matches ); | |
if ( $matched && count( $matches ) == 3 ) { | |
$val = '<a href="' . esc_url( $matches[2][0] ) . '" title="' . esc_attr( $matches[1][0] ) . '">' . sanitize_text_field( $matches[1][0] ) . '</a>'; | |
array_push( $new_values, $val ); | |
} else { | |
array_push( $new_values, $value ); | |
} | |
} | |
} | |
$text = implode( ', ', $new_values ); | |
return $text; | |
} |
What does this code do?
From line 1 to line 67, 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 69 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:
As you can see, there’s a new field at the bottom of the form Add New Designer (Designer 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:
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.
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 first attribute here, Logo, is the local attribute, the second, Designer, is the global attribute.
Now click on Save Attributes and Publish your product. This is how it will appear on the website, using the theme Storefront:
Thanks to James for being my example on this post. I couldn’t use my name because calling me a designer is a shame.
THANK YOU!!! it works!! <3
You’re welcome Luca!
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….
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.
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!
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.
That is a really well thought out post! Does exactly what I was looking for. Many thanks Nicola!
You are welcome Nick!
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!
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
It would be useful adding a targeting option, too, to open target links in a new window.
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
target
for 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.
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
Hey Josh,
I’m not sure to understand what’s happening. Can you please try to explain that again?
Maybe a screenshot would help!
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
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.
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.
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
Hey,
Sorry but I’m not sure what you are trying to do exactly. Can you explain?
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?
Hi Teemu,
It’s possible. In the snippet, replace
<a href="
with<a target="_blank" href="
.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
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?
Was working great up until the latest woocommerce update. Had to remove the code because it caused the site to crash.
Grande Nick, era proprio quello che mi serviva!
Ciao Fra!
Ottimo! 🙂
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
Hello!
Thanks for confirming this!
Have a great summer you too!
Fantastic!
Tested this and confirming it’s working great!
Thanks, Nicola!
You’re welcome!
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!
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
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?
Hello,
You can do that with the widget Layered Nav: https://docs.woocommerce.com/document/woocommerce-widgets/#section-5
Is it possible for your splendid snippet is not working on explorer although everything is perfect for chrome?
Depending on the version of Explorer that you are using, yes it is possible. I never tested it there.
Any opinion for the solution?
This silence seems as “no”?
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!
Nevermind. I Figured it out. Just has to change the input type to text instead of url. Duh.
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!
Hey there. It is a perfect article. But I’d like to use external link. Is this possible?
Oliver
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
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
delete https:// or http:// in url with markdown [text] (url)
I have the same problem…
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.
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.
Any updates on this? As it isn’t currently working. 🙂
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.
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.
plugin file: https://mega.nz/file/3UhnyAZC#FHGXsiM1cqKWIIM23aENU4-3QUjgN043VrvEBlyk-rE
Thank you very much for sharing this, it’s working really great!
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.
This is an absolutely incredible feature that you have provided!
Is there any way to open the links in a new window?
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!
Can you show me how to add link to product attribute label, please ?