admin管理员组

文章数量:1291116

Is there a way to limit the word count of the post title?

I searched over the internet but found nothing.

All I know is, only the content of the post can be limited or excerpted.

Is there a way to limit the word count of the post title?

I searched over the internet but found nothing.

All I know is, only the content of the post can be limited or excerpted.

Share Improve this question edited Dec 11, 2012 at 8:48 fischi 7,5492 gold badges29 silver badges44 bronze badges asked Dec 11, 2012 at 8:18 Juliver GalletoJuliver Galleto 2903 gold badges6 silver badges14 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 8

simply use this where ever you want to display your title with limited words

<?php echo wp_trim_words( get_the_title(), 5 ); ?>

replace number 5 in above code with whatever number of words you need to display.

Regards.

If continue sign "..." needed at end of title

<?php
    echo wp_trim_words( get_the_title(), 10, '...' );
?>

If continue sign "..." not needed at end of title

<?php
    echo wp_trim_words( get_the_title(), 10 );
?>

There is a built-in function for that: wp_trim_words().

add_filter( 'the_title', 'wpse_75691_trim_words' );

function wpse_75691_trim_words( $title )
{
    // limit to ten words
    return wp_trim_words( $title, 10, '' );
}

If you want to trim the words depending on certain properties of the post, ask WP to pass the post ID to your callback. Here is an example for filtering by post type. But you can also check for associated terms, post age or author, and even post meta.

add_filter( 'the_title', 'wpse_75691_trim_words_by_post_type', 10, 2 );

function wpse_75691_trim_words_by_post_type( $title, $post_id )
{

    $post_type = get_post_type( $post_id );

    if ( 'product' !== $post_type )
        return $title;

    // limit to ten words
    return wp_trim_words( $title, 10, '' );
}
function limit_word_count($title) {
    $len = 5; //change this to the number of words
    if (str_word_count($title) > $len) {
        $keys = array_keys(str_word_count($title, 2));
        $title = substr($title, 0, $keys[$len]);
    }
    return $title;
}
add_filter('the_title', 'limit_word_count');

You can put any kind of limit on almost anything you like, you just need the correct filter

本文标签: Limit the word count in the post title