You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改WooCommerce代码将产品属性转为对应归档页链接?

Got it! To turn that "Autor" attribute name into a clickable link pointing to its dedicated archive page, you’ll need to fetch the actual term object (instead of just the display name) and use WordPress/WooCommerce’s built-in functions to generate the correct archive URL. Here’s the modified code and breakdown:

Modified Code

add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
    global $product;
    
    // Fetch the 'Autor' attribute terms for the current product
    // Note: WooCommerce custom attributes use taxonomy slugs prefixed with 'pa_'
    $author_terms = wp_get_post_terms( $product->get_id(), 'pa_autor' );
    
    // Check if we have valid terms to work with
    if ( ! empty( $author_terms ) && ! is_wp_error( $author_terms ) ) {
        echo '<div class="author-product">';
        // Loop through terms (handles multi-select attributes too)
        foreach ( $author_terms as $term ) {
            // Generate the archive URL for the term
            $term_archive_link = get_term_link( $term );
            // Output the linked term name with proper escaping for security
            echo '<a href="' . esc_url( $term_archive_link ) . '">' . esc_html( $term->name ) . '</a>';
        }
        echo '</div>';
    }
}

Key Notes

  • Taxonomy Slug: WooCommerce prefixes all custom product attribute taxonomies with pa_. If your "Autor" attribute has a different slug (e.g., you named it author instead of autor), update pa_autor to match your actual attribute slug (like pa_author).
  • Security: We use esc_url() and esc_html() to sanitize the URL and term name, which is a critical WordPress development best practice to prevent XSS vulnerabilities.
  • Multi-Select Support: The loop handles cases where your "Autor" attribute allows multiple selections. If your attribute is single-select only, you can simplify it by grabbing the first term directly:
    $term = $author_terms[0];
    $term_archive_link = get_term_link( $term );
    echo '<a href="' . esc_url( $term_archive_link ) . '">' . esc_html( $term->name ) . '</a>';
    

内容的提问来源于stack exchange,提问作者Monika Kwiatkowska

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:55:49