Code Snippet
There are times when you may need a shortcode to add the current page or post title somewhere on your site. The various page types that may need to addressed are:
- Pages
- Posts
- Archives (various types)
- Search results
PHP
Place the following code anywhere in your child theme’s functions.php document.
// get page/post title for use on site
function post_title_shortcode() {
if ( is_archive() ) {
$title = get_the_archive_title();
return $title;
}
elseif ( is_search() ) {
$title = get_search_query();
$extended_title = "Search results for: " . $title;
return $extended_title;
}
else {
return get_the_title();
}
}
add_shortcode('post_title','post_title_shortcode');
Note
All modifications to a theme or plugin should be made by creating a child theme and placing the changes there. Changes made to the parent theme will be overwritten the next time it updates.
Now add the following to the page, header, footer, or sidebar where you want the title to appear. You may need to style it or place it within the correct HTML tag (such as an H1 or H2).
WordPress – Add a Page Title to All Page/Post Types
WordPress Notes:
- All modifications to a theme or plugin should be made by creating a child theme and placing the changes there; changes made to the parent theme will be overwritten the next time it updates
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.