在 WooCommerce 单个产品页面上的相关产品标题中添加 relative URL

Add relative URL to related products title on WooCommerce single product page

如果相关产品标题 link 显示更多相关产品会更有意义...

正在尝试将单个产品页面上的相关产品标题更改为 link 与正在显示的相关产品查询相关的最终类别。

我有结束类别的 url 别名和名称我只是无法转义 <h2> 标签将其变成 link。有什么建议吗?

$translated = '<a href="#"> </a>'.esc_html__(end($term_urls).'Continue Browising '.end($term_names), $domain);

add_filter('gettext', 'change_rp_text', 10, 3);
add_filter('ngettext', 'change_rp_text', 10, 3);

function change_rp_text($translated, $text, $domain)
{
global $woocommerce, $post;

 if ($text === 'Related products' && $domain === 'woocommerce') {
     
 $term_names = wp_get_post_terms( $post->ID, 'product_cat', array('fields' => 'names') );
        $term_urls = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'slugs') );
     
     $translated = '<a href="#"> </a>'.esc_html__(end($term_urls).'Continue Browising '.end($term_names), $domain);
 
 }
 return $translated;
 
 }

通常您可以使用 woocommerce_product_related_products_heading 过滤器挂钩,它允许您更改 $heading。但是 $heading 是通过 esc_html() 传递的 所以你不能将 HTML 添加到输出中。

因此您必须覆盖 /single-product/related.php 文件

This template can be overridden by copying it to yourtheme/woocommerce/single-product/related.php.

替换第 29 - 32 行 @version 3.9.0

if ( $heading ) :
    ?>
    <h2><?php echo esc_html( $heading ); ?></h2>
<?php endif; ?>

if ( $heading ) {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get terms
        $terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
        $end = end( $terms ); 

        // URL
        echo '<a href="' . get_term_link( $end->term_id, 'product_cat' ) . '">' . $end->name . '</a>';
    }
}
?>

这似乎无需复制和修改 /single-product/related.php 文件。使用替代方法可能会更有效。

使用@7uc1f3r 提供的答案get_term_link(

add_filter('gettext', 'change_rp_text', 10, 3);
add_filter('ngettext', 'change_rp_text', 10, 3);

function change_rp_text($translated, $text, $domain)
{
global $woocommerce, $post;


 if ($text === 'Related products' && $domain === 'woocommerce') {

        $term_names = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'names') );
        $term_urls = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'slugs') );
        $term_ids = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'ids') );
     

     $last_term_id = end($term_ids);

     $translated = _e('<h2><a href="' . get_term_link( $last_term_id, 'product_cat' ) . '">More ' . end($term_names) . '</a></h2>', $domain);

 }
 return $translated;


}