Site logo

Archived topic

Excerpts word count in Japanese not working

5 replies · Started by naisyo523 on February 24, 2023

Viewing posts 1–6 of 6

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.

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.

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;
});

That worked :) Thank you so much for your help. I'll close this now.

You're welcome! Have great week

This archived topic is closed to new replies.