Site logo

[Resolved] Excerpts word count in Japanese not working

Home Forums Support [Resolved] Excerpts word count in Japanese not working

Home Forums Support Excerpts word count in Japanese not working

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #2545891
    naisyo523

    Hi there,

    I noticed that the “Excerpts word count” in Japanese not working.

    In search of an answer, I found Chinese also had an issue.
    https://docs.generatepress.com/article/fixing-wordpress-excerpts-word-count-in-chinese/

    Could you please provide me with a similar function for Japanese, please?

    Thanks in advance!

    #2546379
    David
    Staff
    Customer Support

    Hi there,

    i am not 100% sure on this but you could try this:

    
    // utility function to check if text is Japanese
    function is_japanese_excerpt($excerpt) {
        $pattern = "/[\p{Han}\p{Katakana}\p{Hiragana}]+/u";
        $matches = array();
        preg_match_all($pattern, $excerpt, $matches);
        if (count($matches[0]) > 0) {
            return true; // excerpt contains Japanese characters
        } else {
            return false; // excerpt does not contain Japanese characters
        }
    }
    // filter the excerpt length
    function custom_excerpt_length($length) {
        $excerpt = get_the_excerpt();
        if (is_japanese_excerpt($excerpt)) {
            return 20; // set Japanese excerpt length to 20 characters
        }
        return $length;
    }
    add_filter('excerpt_length', 'custom_excerpt_length');

    Let me know.

    #2549092
    naisyo523

    Hi there,

    Thanks for this. Unfortunately, when I put this in functions.php, the website does not display (just keep on trying to load the page). I deleted the code and reload the page again, it shows with no issue.

    #2549183
    Jean Paiva
    Developer

    Hey, I created this other filter hope it helps you:

    add_filter('get_the_excerpt', function($excerpt) {
    	$is_japanese = preg_match('/[\x{4E00}-\x{9FBF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}]/u', $excerpt);
    	$excerpt_length = 55;
    
    	if ( $is_japanese && mb_strwidth($excerpt) > $excerpt_length ) {
    		return sprintf( '%1$s %2$s',
    			mb_strimwidth($excerpt, 0, $excerpt_length, ' ', 'UTF-8'),
    			generate_excerpt_more('')
    		);
    	}
    
    	return $excerpt;
    });
    #2549229
    naisyo523

    That worked 🙂 Thank you so much for your help. I’ll close this now.

    #2549239
    Jean Paiva
    Developer

    You’re welcome! Have great week

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.