How to set character limit on the_content() and the_excerpt() in wordpress

后端 未结 9 1333
臣服心动
臣服心动 2020-12-07 23:36

How do I set a character limit on the_content() and the_excerpt() in wordpress? I have only found solutions for the word limit - I want to be able to set an exact amount cha

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 23:48

    wp_trim_words() This function trims text to a certain number of words and returns the trimmed text.

    $excerpt = wp_trim_words( get_the_content(), 40, 'More Link');
    

    Get truncated string with specified width using mb_strimwidth() php function.

    $excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );
    

    Using add_filter() method of WordPress on the_content filter hook.

    add_filter( "the_content", "limit_content_chr" );
    function limit_content_chr( $content ){
        if ( 'post' == get_post_type() ) {
            return mb_strimwidth( strip_tags($content), 0, 100, '...' );
        } else {
            return $content;
        }
    }
    

    Using custom php function to limit content characters.

    function limit_content_chr( $content, $limit=100 ) {
        return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
    }
    
    // using above function in template tags
    echo limit_content_chr( get_the_content(), 50 );
    

提交回复
热议问题