Skip to content

Instantly share code, notes, and snippets.

@gerrgg
Created June 12, 2020 12:48
Show Gist options
  • Save gerrgg/3669e25eca76b1d017a567cad2b1e434 to your computer and use it in GitHub Desktop.
Save gerrgg/3669e25eca76b1d017a567cad2b1e434 to your computer and use it in GitHub Desktop.
How to get a product attribute by name using WC_Product->get_attribute( 'brand' ) and link to attribute archive.
<?php
// Put the product's brand and link to archive above product title on single_product page.
add_action( 'woocommerce_single_product_summary', 'msp_brand_name', 1 );
// Put same link on shop page
add_action( 'woocommerce_before_shop_loop_item_title', 'msp_brand_name', 15 );
function msp_brand_name(){
/**
* Get the product's brand name and link to brand archive
*/
global $product;
// You dont need the 'pa_' prefix. Insert the slug for the product attribute you want.
$brand_slug = 'brand';
$brand = $product->get_attribute( $brand_slug );
// Nothing? STOP.
if( empty( $brand ) ) return;
// If we get this far, we found a brand. (Dont remove the pa_)
$term = get_term_by( 'name', $brand, 'pa_' . $brand_slug );
// Not an archive.
if( $term === false ){
printf( '<div class="product-brand"><span>%s</span></div>', $brand );
} else {
// Found link - is an archive.
$link = get_term_link( $term->term_id );
printf( '<div class="product-brand"><a href="%s">%s</a></div>', $link, $brand );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment