John Davidson

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

0 comments
Message:


It would make a lot more sense if the related products title linked to more of the related products being displayed...


Attempting to change the related products title on the single product page to a link to the end category that correlates to the related products query being displayed.


I have the url slug and name for the end category I just can't escape the <h2> tag to turn it into a link. Any advice?


$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;

}


My Answer:
You are on the right track with your code, but there are a few issues that need to be addressed. Here is a revised version of your code:

php
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'));

$category_url = get_term_link(end($term_urls), 'product_cat');
$category_name = end($term_names);

$translated = 'Continue Browsing ' . $category_name . '';
}

return $translated;
}


In this revised code:
1. I have corrected the syntax for the `if` statement by using `&&` instead of `&&`.
2. I have added the `get_term_link` function to generate the URL for the end category.
3. I have updated the link structure to properly include the category URL and name.

Make sure to replace `'product_cat'` with the correct taxonomy if it is different in your setup. This code should now properly create a link to the end category of the related products on the single product page.

Rate this post

4 of 5 based on 7523 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us