3

I would like to customize the page title of the search result page:

from:

<title>Search Results for “search string” – Page 2 – Sitename</title>

to:

<title>“search string” result page – Page 2 – Sitename</title>

In my search.php template, get_header() is probably the one being called to generate the <title> tag.

Is there a filter that I can apply to it to make this customization?

0

1 Answer 1

4

Within the wp_get_document_title() function we have:

// If it's a search, use a dynamic search results title.
} elseif ( is_search() ) {
        /* translators: %s: search phrase */
        $title['title'] = sprintf( 
            __( 'Search Results for &#8220;%s&#8221;' ), 
            get_search_query() 
        );

so you could hook into the document_title_parts filter to adjust it to your neds.

Example:

/**
 * Modify the document title for the search page
 */
add_filter( 'document_title_parts', function( $title )
{
    if ( is_search() ) 
        $title['title'] = sprintf( 
            esc_html__( '&#8220;%s&#8221; result page', 'my-theme-domain' ), 
            get_search_query() 
        );

    return $title;
} );

Note: This assumes your theme supports title-tag.

Update:

Can I also customize the Page 2 part of the title in the same filter?

Regarding the page part, you can adjust it in a similar way with:

/**
 * Modify the page part of the document title for the search page
 */
add_filter( 'document_title_parts', function( $title ) use( &$page, &$paged )
{
    if ( is_search() && ( $paged >= 2 || $page >= 2 ) && ! is_404() ) 
        $title['page'] = sprintf( 
            esc_html__( 'This is %s page', 'my-theme-domain' ), 
            max( $paged, $page ) 
        );

    return $title;
} );
4
  • Works perfect. One question, I tried to change the domain parameter to my 'child theme slug', 'parent theme slug', and even remove the parameter, they all work. What would be an example of use for the domain parameter in practice? Thanks.
    – KDX
    May 5, 2016 at 12:51
  • An extended question to this, instead of asking another question. Can I also customize the Page 2 part of the title in the same filter? Making it This is 2 page, which may not make sense in plain English, but I'm customizing it into a non-english grammar.
    – KDX
    May 5, 2016 at 12:56
  • Answering my own extended question in the comment. Modifying the return statement to the following will do the trick: return preg_replace('/Page (\d+)/', 'This is $1 page', $title);
    – KDX
    May 5, 2016 at 13:21
  • I added an example for the page part. I added the domain, since the strings are most likely not availabe in the core translation, so it's up to you to translate it. @KDX
    – birgire
    May 5, 2016 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.