在Woocommerce单一产品的标题之前添加链接的特定产品属性

问题描述

在WooCommerce中,我试图在单个产品页面的产品标题之前添加“ pa_artist”产品属性,如下所示:

pa_attribute –产品标题

我希望“艺术家”产品属性术语名称自动标题之前列出。我设法使用this answer code向产品标题添加属性

我需要为“艺术家”产品属性术语名称添加一个活动链接,以显示属性术语名称的产品。

解决方法

基于 Add specific product attribute after title on Woocommerce single products ,您可以轻松地更改代码,以在WooCommerce单个产品页面上的产品标题之前添加特定的产品属性,如下所示:

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>';
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。


添加:对于多个链接的产品属性术语,请改用以下内容:

remove_action( 'woocommerce_single_product_summary',$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>';
    }
}