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:


/**
* 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;
}

view raw

functions.php

hosted with ❤ by GitHub

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:

Add product attribute term 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:

Edit product attribute term form

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:

Editing product attributes on the single product page

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:

How product attributes look like with 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.

59 replies
  1. todd
    todd says:

    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….

    Reply
  2. Jon
    Jon says:

    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!

    Reply
    • Nicola Mustone
      Nicola Mustone says:

      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.

      Reply
  3. Kimberly
    Kimberly says:

    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!

    Reply
  4. Alexander
    Alexander says:

    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

    Reply
    • Nicola Mustone
      Nicola Mustone says:

      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.

      Reply
  5. Josh
    Josh says:

    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

    Reply
  6. Chad
    Chad says:

    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

    Reply
  7. David
    David says:

    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.

    Reply
  8. Mark
    Mark says:

    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.

    Reply
  9. Jayson David
    Jayson David says:

    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

    Reply
  10. Teemu
    Teemu says:

    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?

    Reply
  11. greg
    greg says:

    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

    Reply
  12. Dave
    Dave says:

    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?

    Reply
  13. Ben
    Ben says:

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

    Reply
  14. Jaroslav Ondra
    Jaroslav Ondra says:

    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

    Reply
  15. Leandro
    Leandro says:

    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!

    Reply
  16. Koepi
    Koepi says:

    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

    Reply
  17. Mohammad Goodarzi
    Mohammad Goodarzi says:

    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?

    Reply
  18. Ubiguity
    Ubiguity says:

    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!

    Reply
  19. Alex
    Alex says:

    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!

    Reply
  20. Oliver
    Oliver says:

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

    Oliver

    Reply
  21. faheem
    faheem says:

    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

    Reply
  22. Supriya
    Supriya says:

    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.

    Reply
  23. s10supplies
    s10supplies says:

    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.

    Reply
    • Nicola Mustone
      Nicola Mustone says:

      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.

      Reply
  24. Maio Cape Verde
    Maio Cape Verde says:

    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.

    Reply
  25. improveitsolutions
    improveitsolutions says:

    This is an absolutely incredible feature that you have provided!

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

    Reply
  26. improveitsolutions
    improveitsolutions says:

    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!

    Reply

Trackbacks & Pingbacks

  1. […] 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/ […]

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply