Add linked specific product attribute before title on Woocommerce single products

532 Views Asked by At

In WooCommerce I am trying to add "pa_artist" product attribute before the product title in single product page as below:

pa_attribute – product title

I would like the "artist" product attribute term name to be automatically listed before the title. I managed to add attribute to product title using this answer code.

What I need is to add an active link to the "artist" product attribute term name, that display the products for this attribute term name.

1

There are 1 best solutions below

3
On BEST ANSWER

Based on Add specific product attribute after title on Woocommerce single products you can easily change the code to add a specific product attribute before the product title on WooCommerce single product pages as follows:

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
    global $product;

    $taxonomy     = 'pa_artist';
    $artist_terms = get_the_terms( $product->get_id(), $taxonomy ); // Get the post terms array
    $artist_term  = reset($artist_terms); // Keep the first WP_term Object
    $artist_link  = get_term_link( $artist_term, $taxonomy ); // The term link

    echo '<h1 class="product_title entry-title">';

    if( ! empty($artist_terms) ) {
        echo '<a href="' . $artist_link . '">' . $artist_term->name . '</a> - ';
    }

    the_title();

    echo '</h1>';
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


Addition: For multiple linked product attributes terms use the following instead:

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
    global $product;

    $taxonomy     = 'pa_artist';
    $artist_terms = get_the_terms( $product->get_id(), $taxonomy ); // Get the WP_terms array for current post (product)
    $linked_terms = []; // Initializing

    // Loop through the array of WP_Term Objects
    foreach ( $artist_terms as $artist_term ) {
        $artist_link    = get_term_link( $artist_term, $taxonomy ); // The term link
        $linked_terms[] = '<a href="' . $artist_link . '">' . $artist_term->name . '</a>';
    }
    if( ! empty($linked_terms) ) {
       echo '<h1 class="product_title entry-title">' . implode( ' ', $linked_terms) . ' - ';
       the_title();
       echo '</h1>';
    }
}