Search code examples
wordpressgridtitlearchivestrlen

Shorten the post title url of my grid - archive - page


As the title says I need to shorten the post title of my grid - archive - page. For example, my page title is "20 ways to clean your car. Best hints and tricks 2018." But on the archive page I just want to show "20 ways to clean your car."

I found some code to stop after a certain amount of letters, but I would like to stop if a certain word appears. "Best" for example. Maybe someone can help me.

This is the code i tried so far.

function custom_trim_my_title( $title ) {
if ( strlen( $title ) >= 50 && ! is_singular() ) {
    $title = substr( $title, 0, 50 ) . '...';
    return $title;
}
return $title;
}
add_filter( 'the_title', 'custom_trim_my_title' );

So hopefully someone is able to help me. Thanks in advance.


Solution

  • Try this:

    function custom_trim_my_title( $title ) {
        if ( !is_singular() ) {
            //if you pass $title as "this is a stop", it will return "this is a"
            $new_title = strstr($title, 'stop', true);
            if($new_title) {
                return $new_title;
            }
        }
        return $title;
    }
    add_filter( 'the_title', 'custom_trim_my_title' );