Support » Fixing WordPress » Trim the heading (h1)

  • Is there a way to trim a heading after certain amount of characters?

    Today:
    My long headline

    Instead
    My long head…

Viewing 7 replies - 1 through 7 (of 7 total)
  • That would require some custom code – probably a plugin or a function added to your functions.php file. You’d have to do something where it would find the post title and the code would truncate it for you, then return it for display.

    I’m not good at writing plugins – I’ve done functions though. I don’t know that this will work, but off the top of my head, you’d do something like:

    function truncate_title($string) {
    //get the post title
    $title = get_the_title();
    // set limit at 24 to get 25 characters, since substr starts at "0", not "1"
    $limit = "24";
    $pad="...";
    
    // if the title is shorter than the $limit, do nothing
    if(strlen($title) <= $limit) {
    return $title;
    } else {
    $title = substr($title, 0, $limit) . $pad;
    return $title;
    }
    }

    put that in your functions.php file. Then in your index.php, there it has “the_title” stuff, replace that with “truncate_title()”. Then it *should* filter the title through this function and return it with no more than 25 characters. Of more than 25 characters are in there, then it’ll truncate it as per your request.

    But, like I said, this is NOT tested. You might have to play with it to get it to work. I just totally wrote that off the top of my head – so chances are you’ll have to work with it to make it work (meaning, the first time you use it, you’ll probably get a blank white page on your site because of the errors!) Don’t worry – it’s not going to bust anything permanently. You can always remove it if you can’t make it work 🙂

    Thanks for the quick reply. I´ll have a check on it and see if it works. Thanks again 🙂

    I tried it out and after some fiddling I got it to work. I made a function like you said but made some minor changes. Here is changed function. Thanks for your help!

    function truncate_title() {
    //get the post title
    $title = get_the_title();
    // set limit at 24 to get 25 characters, since substr starts at "0", not "1"
    $limit = "27";
    $pad="&hellip;";
    
    // if the title is shorter than the $limit, do nothing
    if(strlen($title) <= $limit) {
    echo $title;
    } else {
    $title = substr($title, 0, $limit) . $pad;
    echo $title;
    }
    }

    awesome! Glad it worked then 🙂

    Thank you two guys, I’v been looking for this method for many days. Thanks a lot.

    But how do I truncate %link in next_post_link:
    <?php next_post_link(‘Nex Post:%link’,’%title’,true) ?>

    Awesome. This came in VERY handy. Exactly what I needed.
    I’m learning so much PHP via wordpress as an applicable example.
    THANK YOU BOTH!

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Trim the heading (h1)’ is closed to new replies.