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

Redirect wordpress search query if its a tag

programmeradmin2浏览0评论

i have modified this function to make it redirect search query if it a tag

example if searchQuery='football' then redirect to /tag/football/

function redir_search($a) {
  if (is_search()) {
    global $wp_query;
    $s_str = $wp_query->query_vars['s'];
    if(!empty($s_str)) {
    if ( term_exists($s_str, 'post_tag' ) ) {
        $url = get_home_url().'/tag/'.$s_str.'/';
        wp_safe_redirect($url);
        exit();
     }
    }
  }
}
add_filter('template_redirect','redir_search'); 

this function works, it does what i need but is this a good way to do it? why do i have a feeling like it perform the search then it redirect? (i want it to immediatly redirect, without searching)

i put the function inside theme functions.php

i have modified this function to make it redirect search query if it a tag

example if searchQuery='football' then redirect to /tag/football/

function redir_search($a) {
  if (is_search()) {
    global $wp_query;
    $s_str = $wp_query->query_vars['s'];
    if(!empty($s_str)) {
    if ( term_exists($s_str, 'post_tag' ) ) {
        $url = get_home_url().'/tag/'.$s_str.'/';
        wp_safe_redirect($url);
        exit();
     }
    }
  }
}
add_filter('template_redirect','redir_search'); 

this function works, it does what i need but is this a good way to do it? why do i have a feeling like it perform the search then it redirect? (i want it to immediatly redirect, without searching)

i put the function inside theme functions.php

Share Improve this question asked May 6, 2020 at 22:07 Mo XMo X 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

To do it in query handling stage, may use request hook which is when WordPress query is being setup.

The term link is recommended by @Jacob Peattie using built-in get_term_link() instead of building it manually for more flexibility and error-proof.

add_filter( 'request', 'ws366006_check_request_query' );
function ws366006_check_request_query( $query ) {
    // var_dump($query);

    // redirect checking
    if( ! empty( $query['s'] ) ) {
        $search = $query['s'];
        if ( term_exists( $search, 'post_tag' ) ) {
            $url = get_term_link( $search, 'post_tag' );
            wp_safe_redirect( $url );
            exit();
         }
    }

    // normal return
    return $query;
}

If want to use custom query parameters that is not publicly available in WordPress, just add it to the allowed list by query_vars hook.

add_filter('query_vars', 'ws366006_add_query_vars' );
function ws366006_add_query_vars( $query_var ) {
    $query_var[] = 'searchQuery';
    return $query_var;
}
发布评论

评论列表(0)

  1. 暂无评论