最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Merge two search functions for custom post type

programmeradmin1浏览0评论

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

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');
Share Improve this question edited Sep 19, 2019 at 23:44 Stickers asked Sep 19, 2019 at 22:09 StickersStickers 2521 gold badge6 silver badges17 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论