skip to Main Content

I am using the below code that Automatically shortens WooCommerce product titles on the static home page main shop, category, and tag pages. I want to do also that for related products. what conditional tag should i add for related product here

This code automatically shortens WooCommerce product titles on the static home page main shop, category, and tag pages to a set number of characters

function short_woocommerce_product_titles_chars( $title, $id ) {
    if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() ) && get_post_type( $id ) === 'product' ) {
        // Kicks in if the product title is longer than 60 characters 
        if ( strlen( $title ) > 60) {
            // Shortens it to 60 characters and adds ellipsis at the end
            return substr( $title, 0, 60 ) . '...';
        }
    }

    return $title;
}
add_filter( 'the_title', 'short_woocommerce_product_titles_chars', 10, 2 );

2

Answers


  1. You can check this article. Hope it will be solve your issues.
    https://designsmaz.com/how-to-short-woocommerce-products-title/#comment-76957

    Login or Signup to reply.
  2. The following will extend your current code to related product too:

    function shorten_woocommerce_loop_product_titles( $title, $id ) {
        global $woocommerce_loop;
    
        if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() || ( isset($woocommerce_loop['name'])
        && $woocommerce_loop['name'] === 'related' ) ) && get_post_type( $id ) === 'product' ) {
            $length_threshold = 60; // Here define the desired number of characters max to be displayed
    
            // If the product title is longer than xx characters 
            if ( strlen( $title ) > $length_threshold ) {
                // Shortens it to xx characters and adds ellipsis at the end
                return substr( $title, 0, $length_threshold ) . '...';
            }
        }
        return $title;
    }
    add_filter( 'the_title', 'shorten_woocommerce_loop_product_titles', 10, 2 );
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search