如何修改WooCommerce代码将产品属性转为对应归档页链接?
Solution: Link Product Attribute to Its Archive Page
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 itauthorinstead ofautor), updatepa_autorto match your actual attribute slug (likepa_author). - Security: We use
esc_url()andesc_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
相关产品推荐
相关产品推荐

