Last active
April 28, 2019 11:22
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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