0

In several post titles I have "years" (eg: "Lorem ipsum - 2018"), it's not a problem. But in another part of the blog I call these titles in PHP:

$shortitle = wp_html_excerpt( get_the_title(), 23, '...' ); <div class="col-md-9">' . $shortitle . '</div>.

How could I remove the display of years in titles ? Thank you :)

Update:

Found the function str_replace, but it's weird for my case:

    $title_long = get_the_title();
    $excludeyears = array(" - 2017", " - 2018", " - 2019", " - 2020");
    $title_long_exclude_years = str_replace($excludeyears, "", $title_long);    

    $shortitle = wp_html_excerpt( $title_long_exclude_years, 23, '...' );

it displays:

Lorem ipsum – 201...

Update 2:

Okay, it's a problem with "-" character, but I dont have a solution.

1

Yes the problem is with the hyphen. WordPress converts hyphens with with spaces to en-dash. Following is the conversion with hyphens with WordPress:

  1. Foo {3 hyphens, spaced} Bar → Foo — Bar (em-dash)
  2. Foo{3 hyphens, no space}Bar → Foo—Bar (em-dash)
  3. Foo {2 hyphens, spaced} Bar → Foo — Bar (em-dash)

  4. Foo{2 hyphens, no space}Bar → Foo–Bar (en-dash)

  5. Foo {1 hyphen, spaced} Bar → Foo – Bar (en-dash)

Refer here for this.

For your specific issue, you can do the following. This has a limitation that date should be at the last of the title.

// WP converts hyphens with spaces to n-dash, so convert them to hyphen again.
$title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', get_the_title() );
// Explode using hyphen;
$title =  explode( '-', $title );
// Remove last element i.e date.
array_pop( $title );
// Convert array to string.
$title = implode( $title );
// Echo.
echo $title;

OR you can do the same using regex like the following which do not have the limitation as above:

        // WP converts hyphens with spaces to n-dash, so convert them to hyphen again.
        $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', get_the_title() );

        // Pattern for date with hyphen and space.
        $pattern = '(\s\W\s\d+)';

        // Replace with space.
        echo preg_replace( $pattern, ' ', $title );
  • Thank you for this long explanation. I understand better and it works! – Garrosh Nov 14 '17 at 15:49
0

I am making an assumption that all the titles have same pattern, i.e hyphen followed by the year.

$title_long = get_the_title();
$title = explode('-' , $title_long);
$title = trim($title[0]);
$shortitle = wp_html_excerpt( $title, 23, '...' );

I guess this would do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.