In addition to the site-wise search. I have a custom search for a certain post type and with different ordering than the global search. Here are the two function, which works. I wonder if those two can be merged into one, or simplified if possible?

function _s_staff_search($template) {
    global $wp_query;
    if ($wp_query->is_search && 'staff' === get_query_var('post_type')) {
        $template = get_template_part('template-parts/staff-search');
    return $template;
add_filter('template_include', '_s_staff_search');

function _s_staff_query($query) {
    if ($query->is_search() && 'staff' === get_query_var('post_type')) {
        $query->query_vars['orderby'] = 'name';
        $query->query_vars['order'] = 'ASC';
add_filter('parse_query', '_s_staff_query');

Your functions are already simple enough, and secondly, the functions do different things:

  • _s_staff_query() filters the posts query variables and the function has to run before WP_Query queries the database.

  • _s_staff_search() filters the search results template and the function has to run after WP_Query queries the database.

So just keep them independent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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