How to customize search result page title?

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 “%s”' ), 
            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__( '“%s” 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 Comment

tech