D
D
Damaks2016-05-20 22:47:38
Taxonomy
Damaks, 2016-05-20 22:47:38

How to make a request using the request hook?

On the Internet, I found a way to change the url of headings. For example, changing " /category/cat_old/ " to " /category/cat_new/ ":

add_filter('request', 'my_request', 9999, 1);
function my_request($query){
  $url = urldecode($_SERVER['REQUEST_URI']);
  if ($url == '/category/cat_new/')
    $query['category_name'] = 'cat_old';
  return $query;
}

I need to do the same with a custom taxonomy, where "tax" is the taxonomy, "term" is the taxonomy term. By analogy, replace the link " /tax/term_old/ " with " /tax/term_new/ ".
How to replace " $query['category_name'] = 'cat_old' " in that case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Laid, 2016-05-21
@stoik_kpd

Admin panel: settings - permalinks - enter in the required line: /category/cat_new/
---------------

add_filter('request', 'my_request', 9999, 1);
function my_request($query){
  $url = urldecode($_SERVER['REQUEST_URI']);
  if ($url == '/tax/term_new/')
    $query['название таксономии'] = 'название термина';
  return $query;
}

Try like this

D
Damaks, 2016-05-21
@Damaks

Full code:

// перезаписываем ссылки
add_filter('term_link', 'sm_term_links', 10, 3);
function sm_term_links($url, $term, $taxonomy){
  $replace = $term->slug;
  /* нужно указать ID и новый ярлык */
  if ($term->term_id == 7)
    $replace = 'term_new';
  $url = str_replace($term->slug, $replace, $url);
  return $url;
}

// перезаписываем основной запрос
add_filter('request', 'sm_request', 9999, 1);
function sm_request($query){
  $url_zapros = urldecode($_SERVER['REQUEST_URI']);
  if ($url_zapros == '/tax/term_new/')
    $query['tax_name'] = 'term_old';
  return $query;
}

// ставим 301 редирект со старых ссылок на новые
add_action('template_redirect', 'sm_301_redirect');
function sm_301_redirect() {
  /* старые=>новые ссылки  */
  $rules = array(
    array('old'=>'/tax/term_old/','new'=>'/tax/term_new/') // рубрика
  );
  foreach ($rules as $rule) :
    // если URL совпадает с одним из указанных в массиве, то редиректим
    if (urldecode($_SERVER['REQUEST_URI']) == $rule['old']) :
      wp_redirect(site_url($rule['new']), 301);
      exit();
    endif;
  endforeach;
}

P, S,
The question is no longer relevant. Solved the problem in a different way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question