Limit Post Excerpt Length In English And Chinese Edition For WordPress

Outline

    Original Post

    Limit Post Excerpt Length In English And Chinese Edition For WordPress


    Orignal Post

    Limit Post Excerpt Length In English And Chinese Edition For WordPress


    Post preview, also called Excerpt in WordPress. There are some ways to limit the length of except.

    The Most Common Way

    function custom_excerpt_length( $length ) {
        return 50;
    }
    add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

    The most common code is above. However, it comes with another issue, if you defined a custom excerpt, the length of it wouldn’t be limited. In other words, it will show completely.

    The Better Way For Multilingual Sites

    The way to calculate words is different in each language. The typical types are alphabet language and character language. The former is like English, and latter is like Chinese. As a result, you can place this code in your template. Notice that I used Polylang to create my multilingual site, so you have to modify the second line if you use other plug-in, like WPML.

    // Function from Polylang
    $cur_lang = get_bloginfo("language")
    
    // Excerpt Length Limit
    if ($cur_lang == 'zh-TW') {
      $limit = 70;
      $excerpt = strip_tags(get_the_excerpt());
      $excerpt = mb_substr($excerpt, 0, $limit);
    }elseif ($cur_lang == 'en-US') {
      $limit = 120;
      $excerpt = strip_tags(get_the_excerpt());
      $excerpt = mb_substr($excerpt, 0, $limit);
    }
    
    echo '<p>'.$excerpt.'...</p>';
    

    And you can test the string length with this code.

    echo '<p>'.mb_strlen('亞倫害的').'</p>'; // Chinese Version
    echo '<p>'.strlen('E-book Reader Intro').'</p>'; // English Version

    Notice that I add … between the p tags, I used it as my read more text. And if you add this code in your function.php, remove it, or … will display twice on your automatically generated excerpts. Refer here, 〈Customize Read More Text In WordPress Excerpt〉.

    function custom_excerpt_more($more) {
         return '';
     }
     add_filter('excerpt_more', 'custom_excerpt_more');

    Related Posts

    The Complete WordPress Customization Tutorial – Just Copy And Paste And Work



    Related Posts

    Aron

    A data scientist working in a retail company, with experience in web design and marketing. Recently dives into cryptocurrency and quantitative investing.

    facebook telegram
    Content Protection by DMCA.com

    Leave a Reply

    • Required fields are market * .
    • Your email address will not be published.
    • Please ensure your email address is correct, then you will get a notification once a new comment reply.

    Your email address will not be published. Required fields are marked *