Skip to content

Render shortcode in title in menu and post/page but strip shortcode for page title

the sun is setting over a mountain range

If you use shortcodes in post titles they might not be rendered or if they are rendered they might not create a proper result or might not be suitable for being a title in the source code because HTML should not be in a title.

Still, I have titles in a page where there is a special icon. A shortcode that creates HTML output to render that icon. But now I faced the problem that I do not want HTML in the site title in the source, but I want that HTML in the actual inline title top of the post or page.

Shortcodes in titles can be problematic – How to fix this.

Here are three snippets that help to achieve this. The two above force to render the shortcode in the post/page title and in the menu but the third snippet strips the shortcode from the page title in the <title> HTML tag in the source. So you now have the best from both world.

// Render shortcode in the page/ post titles.
add_filter('wp_title', 'do_shortcode', 10);
add_filter('the_title', 'do_shortcode', 10);

// Render shortcode in the menu.
add_filter('walker_nav_menu_start_el', 'do_shortcode', 10);

// Strip shortcode from the actual html page title
function custom_title($title_parts) {
	$title_parts['title'] = strip_shortcodes( $title_parts['title'] );
    return $title_parts;
}
add_filter( 'document_title_parts', 'custom_title' );

Dieser Beitrag hat 0 Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

An den Anfang scrollen