theme development - How can you set up the base url for search to be a child page of the home page?

admin2025-05-31  0

I am running into an issue with my site when trying to use the out of the box search function, only having the searchform.php set to a child page of my Home page.

<form role="search" method="get" action="<?php echo esc_url( home_url( '/page-two/' ) ); ?>">
    <div class="d-flex search-bar">
        <input class="search-field" type="search" name="s" value="<?php the_search_query(); ?>" id="search-input" placeholder="Search...">
        <button class="btn search-submit" type="submit">
            <i class="fa fa-search" aria-hidden="true"></i>
        </button>
    </div>
</form>

I've set up my custom filter to limit the search results to all of the pages under my page-two in the site.

function limit_search_to_sections($query) { 

    if ($query->is_search && !is_admin()) {
        // Limit the query to pages
        $query->set('post_type', 'page');
        // Limit to those pages with a specific parent ID
        $query->set('post_parent', 12345); // Replace with your parent page ID
    }

    return $query;
}

add_filter('pre_get_posts','limit_search_to_sections');

The issue is that when I attempt to enter a search, no search results are appearing on the page.

In fact, when I output the query, it's showing the query is for is_page and is_singular instead of the is_search.

Now, if I change the action of my searchform.php to <?php echo esc_url( home_url( '/' ) ); ?> then the search works, as expected, except it shows up a the home url instead of my child page url.

I do have a search.php template created too.

Is there anyway I can have the search display on the child page?

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748630103a313649.html

最新回复(0)