Skip to content

Instantly share code, notes, and snippets.

@glueckpress
Last active April 28, 2019 11:22
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 glueckpress/2702422 to your computer and use it in GitHub Desktop.
Save glueckpress/2702422 to your computer and use it in GitHub Desktop.
[WordPress] Add Bootstrap sub-heading to post title. Simply write something like "My post title | Smaller sub-line added here." into your post title or widget title field.
<?php
/**
* Append a sub-heading to WordPress post titles
*
* Input: My title | my sub-title
* Output: My title <small>my sub-title</small>
*
* The filter the_title() is used for posts/pages AND nav menus in WordPress.
* In order to filter only post/page titles, not nav menu items, we need to
* switch the title filter off when the menu class starts and back on when it ends.
*
* Toscho has created a life-saving example at WordPress StackExchange: http://bit.ly/Res0ci
* I just had to switch the on/off statement and add the actual filter function.
* Also added a filter for single_post_title() which is used by wp_title() to demonstrate how
* to manipulate the <title> element within <head>. Outcomment/delete it as you see fit.
*/
add_filter( 'wp_nav_menu_args', 'gp121028_title_filter_switch' );
add_filter( 'wp_nav_menu', 'gp121028_title_filter_switch' );
add_filter( 'single_post_title', 'gp121028_filter_single_post_title' ); // for demo purposes only
/**
* Switch title filter off when menu class starts and on when it ends.
*
* @param mixed $input Array or string, we just pass it through.
* @return mixed
*/
function gp121028_title_filter_switch( $input ) {
$func = 'wp_nav_menu_args' == current_filter() ? 'remove_filter' : 'add_filter';
$func( 'the_title', 'gp121028_filter_title' );
return $input;
}
/**
* Filter function for the_title()
*/
function gp121028_filter_title( $title ) {
$substrings = explode( ' | ', $title );
$title = ( ! empty( $substrings[0] ) ) ? $substrings[0] . '<small>' . $substrings[1] . '</small>' : $title;
return $title;
}
/**
* Filter function for single_post_title()
*/
function gp121028_filter_single_post_title( $title ) {
$substrings = explode( ' | ', $title );
$title = ( ! empty( $substrings[1] ) ) ? $substrings[0] . ' (' . $substrings[1] . ')': $title;
return $title;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment