Wordpress Titles: If Longer Than 50 Characters, Show Ellipsis

前端 未结 9 1314
谎友^
谎友^ 2021-02-01 19:06

I have a wordpress site with titles, and if the title has more than 50 characters I need to add an ellipsis (...) at the end of the title and stop the title at 50 characters. Be

相关标签:
9条回答
  • 2021-02-01 19:36
    echo (strlen(the_title())>50) ? (substr(the_title(), 0, 50) . "...") : the_title());
    

    This is a ternary operator. What it basically says is if the result from the_title() is more than 50 characters, then echo the first 50 characters and then the string .... Otherwise, just echo the result from the_title().

    You can read more about substr here: http://php.net/manual/en/function.substr.php

    You can find info on the ternary operator here: http://php.net/manual/en/language.operators.comparison.php

    0 讨论(0)
  • 2021-02-01 19:44

    WordPress has built in function "wp_trim_words()" to trim the sentences based on the number of words you provide, If you want to trim by words then this function may help you.

    https://codex.wordpress.org/Function_Reference/wp_trim_words

    to trim the title longer than 5 words you can do this

    <?php
    $title = get_the_title();
    $short_title = wp_trim_words( $title, 5, '...' );
    echo '<h3>'.$short_title.'</h3>';
    ?>
    
    0 讨论(0)
  • 2021-02-01 19:45

    use 'strlen'

    eg: 
    
      <?php echo ((strlen(get_the_title())>50) ? (substr(get_the_title(), 0, 50) . "...") : get_the_title())?>
    
    0 讨论(0)
提交回复
热议问题