Site logo

[Resolved] Number of characters in post title

Home Forums Support [Resolved] Number of characters in post title

Home Forums Support Number of characters in post title

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #1856698
    Roger

    Hi,

    I’m using this code to limit the number of characters in the post title. It’s working on both the archive page and the single post page.

    How to limit the number of characters on archive page only?

    This code is in function.php

    function max_title_length( $title ) {
    $max = 20;
    if( strlen( $title ) > $max ) {
    return substr( $title, 0, $max ). "…";
    } else {
    return $title;
    }
    }

    This code is in archive.php
    add_filter( 'the_title', 'max_title_length');

    #1856756
    David
    Staff
    Customer Support

    Hi there,

    in your function, change this line:

    if( strlen( $title ) > $max ) {

    to:

    if( is_archive() && strlen( $title ) > $max ) {

    #1856781
    Roger

    Great!

    Thank you!

    #1857037
    David
    Staff
    Customer Support

    You’re welcome

    #2282354
    Filip

    Hello!

    I tried adding the things mentioned above, but it doesn’t work for me. I have a child theme and want to limit characters on archive pages.

    functions.php code:

    function max_title_length( $title ) {
    $max = 20;
    if( is_archive() && strlen( $title ) > $max ) {
    return substr( $title, 0, $max ). "…";
    } else {
    return $title;
    }
    }

    arhive.php code:

    add_filter( 'the_title', 'max_title_length');

    Can you tell me what’s wrong?

    Thanks!

    #2282378
    David
    Staff
    Customer Support

    Hi there,

    this code:

    add_filter( 'the_title', 'max_title_length');

    Remove that from the archive.php and it into your functions.php, before or after the other code will do.

    #2282382
    Filip

    Hello!

    Still doesn’t work.

    Looks like this now:

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

    Here’s the archive page.

    I’ve also tried placing the code above the first one.

    #2282419
    David
    Staff
    Customer Support

    Try this snippet instead:

    add_filter( 'the_title', function( $title ){
        $max  = 20;
        if ( !is_archive() || !is_home() || $max > strlen( $title ) ) {
            return $title;
        }
        return substr( $title, 0, $max ) . "…";
    }, 10, 2 );

    Note – the_title function in WordPress is used in lots of places from menus to widgets. So this may affect other elements on the page.

Viewing 8 posts - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.