1

I know that WordPress can filter shortcodes like the_content but is it possible to filter get_the_content?

I have a function that is able to use substr and strpos and I know it works on the_title. I tried the same thing for get_the_title but I couldn't get it to work.

Is it possible for the same to work on get_the_title?

Code I have so far:

function gg_short_title($title) {
// This can return false, so check there is something
$linkt=array();
$linkt[] = substr($title, 0, strpos($title, ' —'));
$linkt[] = substr($title, 0, strpos($title, ' –'));
$linkt[] = substr($title, 0, strpos($title, ' |'));
$linkt[] = substr($title, 0, strpos($title, ' -'));
$short_title = implode('', $linkt);
if ($short_title) {
    return $short_title;
}

// Else just return the normal title
return $title; 
} 
add_filter('get_the_title', 'gg_short_title', 10, 1);

Thanks.

4
  • Can you give an example of the title input and expected output? It looks like you're trying to do something with a title containing an em dash, en dash, vertical bar, or a regular dash.
    – cowgill
    Commented Oct 30, 2016 at 1:23
  • Title before: AMD reveals Radeon Pro 400 series GPU specs, as used in new MacBook Pro | Ars Technica Title after: AMD reveals Radeon Pro 400 series GPU specs, as used in new MacBook Pro Commented Oct 30, 2016 at 1:42
  • Yep. Didn't work $linkt[] = substr($title, 0, strpos($title, ' —')); $linkt[] = substr($title, 0, strpos($title, ' –')); $linkt[] = substr($title, 0, strpos($title, ' |')); $linkt[] = substr($title, 0, strpos($title, ' -')); $linkt[] = substr($title, 0, strpos($title, ' —')); $linkt[] = substr($title, 0, strpos($title, ' |')); Commented Oct 30, 2016 at 3:27
  • Thx. Did you also try matching against HTML all entities (e.g. —, etc)?
    – cowgill
    Commented Oct 30, 2016 at 3:29

2 Answers 2

2

The function the_title() is just a wrapper around the function get_the_title().

It's understandably confusing that the filter the_title actually exists inside get_the_title(). So, whatever the function you're using to actually display it, it doesn't matter, you can filter its content by hooking into the_title

3

In addition to moraleida's answer, here's a shorter way to match and output your titles.

Note - It will split the string on the first match it finds so if there are multiple '|' or 'em dash' characters, that could be a problem (even for your original code).

function gg_short_title( $title ) {

  if ( 1 === preg_match( '(—|–|||-|\|)', $title, $matches ) ) {
    $short_title = explode( $matches[0], $title, 2 );
    $title = trim( $short_title[0] );
  }

  return $title;
}
add_filter( 'the_title', 'gg_short_title', 10, 1 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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