Christian Mayne
Christian Mayne

Reputation: 1749

Getting the Product Attribute Term Permalink in WordPress / WooCommerce

I'm using WooCommerce with WordPress to build a store of Antique Photos.

I'm using the WooCommerce product attributes feature to store information about an item photographer.

See here for an example, photographer attribute is pulled out in the box on the left http://bit.ly/1Dp999O

The code that pulls out the attribute looks like this:

if($attribute['is_taxonomy']) {
  $values=wc_get_product_terms($product->id, $attribute['name'], array('fields' => 'names'));
  echo apply_filters('woocommerce_attribute', wpautop(wptexturize(implode(', ', $values))), $attribute, $values);
}

$values looks like this:

Array ( [0] => Photographer 1 )

The problem is, how do I get to the permalink for the Photographer which is automatically generated by WordPress and WooCommerce: http://bit.ly/1JtwBna

I can't find any documentation for this within WooCommerce, and this seems to be a taxonomy within a taxonomy which goes a bit further than stabdard WordPress, but I'm assuming this is a fairly standard requirement. Any pointers appreciated.

Upvotes: 3

Views: 8480

Answers (2)

helgatheviking
helgatheviking

Reputation: 26319

Once you have the attribute term (in this case the photographer's name) you can use get_term_link() to get the URL. Because the $product id isn't passed to the woocommerce_attribute folder, I couldn't filter that, but instead create an override of the product-attributes.php template. And modified the relevant section to be the following:

if ( $attribute['is_taxonomy'] ) {

    $terms = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'all' ) );

    $html = '';
    $counter = 1;
    $total = count( $terms );

    foreach( $terms as $term ){ 

        $html .= sprintf( '<a href="%s" title="Permalink to %s">%s</a>', 
            esc_url( get_term_link( $term ) ), 
            esc_attr( $term->name ), 
            wptexturize( $term->name ) 
        );

        if( $counter < $total ){
            $html .= ', ';
        }
        $counter++;

    }

    echo wpautop( $html );

}

For some reason, the URL isn't a pretty permalink. It's late and I can't tell if this has to do with my configuration or what exactly, but it is a start.

Upvotes: 5

Christian Mayne
Christian Mayne

Reputation: 1749

This basically does what I require:

$terms = get_the_terms($product->id, $attribute['name']);
foreach ($terms as $term){
    echo '<a href="'.get_term_link($term->slug, $term->taxonomy).'">'.$term->name.'</a>';
}

But could do with a bit of refinement for sure.

Upvotes: 3

Related Questions