• Hi
    I’m using the following code to truncate the titles on the blog page:

    function max_title_length( $title ) {
    $max = 18;
    if (strlen( $title ) > $max && get_post_type() == 'post') {
    return substr( $title, 0, $max ). " …";
    } else {
    return $title;
    }}
    
    add_filter( 'max_title_length', 'title' );

    (edit) I’ve found an alternative with CSS so you won’t see it happening on the site but I’d like to find the answer if I can as I’m trying to get better at PHP

    It’s working but not on the first title. Do I need to add something else?

    The page I need help with: [log in to see the link]

Viewing 6 replies - 1 through 6 (of 6 total)
  • This line doesn’t make sense
    add_filter( 'max_title_length', 'title' );

    How is it working? Do you call apply_filters? Do you have a function called title?

    Thread Starter harmlessvikmartin

    (@harmlessvikmartin)

    Ok – changing it to apply_filters has worked. Thanks.

    I added title because it wanted 2 parameters

    Thread Starter harmlessvikmartin

    (@harmlessvikmartin)

    Oh – no it didn’t I’m lying. It was my CSS that was working…

    So the answers are no and no

    Please don’t edit your question to change the question. It makes the replies very confusing.

    Read this page for how to use add_filter
    https://developer.wordpress.org/reference/functions/add_filter/

    You can use existing WordPress filters that are invoked with apply_filters, or you can change the code where it is output(like in the theme) to call your function.

    Thread Starter harmlessvikmartin

    (@harmlessvikmartin)

    Ok – Thanks.

    I haven’t edited my question since you before you first replied.

    If anyone is up for helping me to solve my immediate problem while I carry on learning php I’d be very grateful.

    Just to clarify, I am asking what I need to add to this code to make it apply to the first post in the list as well as the subsequent ones.

    I now know that the last line was wrong, but I don’t think that is what is causing the problem as removing it has no effect.

    Moderator bcworkz

    (@bcworkz)

    The solution depends on how your theme outputs the post title. If it uses the_title(); or echo get_the_title();, you can use “the_title” filter, like so:
    add_filter('the_title', 'max_title_length');

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘truncate first post title’ is closed to new replies.