Skip to content

Instantly share code, notes, and snippets.

@greghunt
Last active March 13, 2018 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greghunt/32291bf60d07ed00a609 to your computer and use it in GitHub Desktop.
Save greghunt/32291bf60d07ed00a609 to your computer and use it in GitHub Desktop.
No WP orphans
<?php
function no_orphans( $title ) {
global $post;
if( $title == $post->post_title ){
//Take apart
$title_words = explode(' ', $title);
$tile_without_last_word = array_slice($title_words, 0, -1);
$last_word = array_slice($title_words, -1, 1);
//Put back together
$new_title = implode(' ', $tile_without_last_word);
//add in non-breaking space
$new_title .= '&nbsp;' . $last_word[0];
$title = $new_title;
}
return $title;
}
add_filter( 'the_title', __NAMESPACE__ . '\\no_orphans', 10, 2 );
@jetlej
Copy link

jetlej commented Feb 8, 2015

Very nice :)

@greghunt
Copy link
Author

greghunt commented Mar 13, 2018

A jQuery equivalent:

$(".title").each(function(){
  var words = $(this).text().trim().split(" ");
  if( words.length > 1 ) {
    var firstWord = words.shift();
    var lastWord = words.pop();
    var formattedText = firstWord + '\xa0' + words.join(" ") + '\xa0' + lastWord;
    $(this).text(formattedText);
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment