How to add search result title to page hero on generatePress Sites

Updated on:

The search results page is a crucial element of any website that allows users to find relevant information quickly and efficiently. However, when you use a block element – page hero to display on a search result page, GB or GP’s dynamic option can NOT output the correct search query, instead, it outputs the title of the first post. In this article, we will explore how to dynamically output the search results title by adding a dynamic headline and a PHP snippet. By implementing this solution, you can provide users with a more informative and engaging search experience.


1. Create a shortcode for search query

The below PHP code creates a shortcode [yh_serach_query] which will output the search query on the search result page. You can change the $pre_fix text to fit your need.

add_shortcode( 'yh_serach_query', function() {
    $search_query = get_search_query();
    $pre_fix = 'Search result for: ';
    echo $pre_fix.$search_query;
    return ob_get_clean();
} );

2. Add the shortcode to the search result page hero element

You can paste the shortcode directly into a GB headline block with all the styles set, no need to use a shortcode block in this case.

3. remove the original theme search result title

GP’s page hero element can not remove the default search result archive title, so you will end up with 2 search results titles. To remove the original one, use this PHP code:

add_action('wp',function () {
    remove_action( 'generate_before_loop', 'generate_do_search_results_title' );