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?

1 Answer
1

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;
} );

Leave a Reply

Your email address will not be published. Required fields are marked *