【问题标题】:Add linked specific product attribute before title on Woocommerce single products在 Woocommerce 单品的标题前添加链接的特定产品属性
【发布时间】:2020-10-09 09:45:08
【问题描述】:

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

pa_attribute – 产品标题

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

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

【问题讨论】:

标签: php wordpress woocommerce product taxonomy-terms


【解决方案1】:

基于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', '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>';
    }
}

【讨论】:

  • 感谢您的意见,LoicTheAztec!您提供的代码将属性添加到产品标题,但我需要将其作为具有活动链接的属性发布在标题之前,就像我最初的帖子中的示例一样。
  • @Solarside 我已更新我的答案代码以包含指向产品属性术语名称的链接...如果此答案回答了您的问题,请accept 回答,谢谢。
  • 谢谢,它成功了!当产品具有多个属性值时,您能否帮助使其工作,例如 value 1 / value 2 - product title
  • @Solarside 我在答案中添加了一个补充内容。
猜你喜欢
  • 2018-12-14
  • 2018-05-04
  • 1970-01-01
  • 2022-01-02
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
相关资源
最近更新 更多