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
- Products
- Custom Post Types
- Archives (various types)
- Search results
PHP
Place the following code anywhere in your child theme’s functions.php document.
// get page/post title for header
function get_the_custom_title() {
if (is_singular()) {
return '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
}
elseif (is_archive()) {
return '<a href="' . get_permalink() . '">' . get_the_archive_title() . '</a>';
}
elseif (is_search()) {
return "Search results for: " . get_search_query();
}
elseif (is_home()) {
return '<a href="' . get_permalink(get_option('page_for_posts')) . '">News</a>';
}
elseif (is_front_page()) {
return '<a href="' . home_url() . '">' . get_bloginfo('name') . '</a>';
}
else {
return '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
}
}
add_shortcode('my_post_title','get_the_custom_title');
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).
[my_post_title]
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.