M
M
m4son2020-05-01 10:39:24
WordPress
m4son, 2020-05-01 10:39:24

How to remove default post type link in wordpress?

Created a custom post type service and a taxonomy for it service_category.
According to the assignment, it was necessary to make a link sitename.ru/category name/post name.
And now the post type is available via 2 links: sitename.ru/category_1/service_1 and sitename.ru/service/service_1
With the same taxonomy sitename.ru/category_1/ and sitename.ru/service_category/category_1
How to remove these duplicates with labels? The SEO says it's very bad

Here is the code I used to change the links

// смена запроса
add_filter('request', 'true_smenit_request_3', 1, 1);

function true_smenit_request_3($query)
{

  $taxonomia_name = 'service_category'; // укажите название таксономии здесь, это также могут быть рубрики category или метки post_tag

  // запросы для дочерних элементов будут отличаться, поэтому нам потребуется дополнительная проверка
  if ($query['attachment']) :
    $dochernia = true; // эту переменную задаём для себя, она нам потребуется дальше
    $urlyarlyk = $query['attachment']; // это ярлык данного термина/рубрики/метки
  else :
    $dochernia = false;
    $urlyarlyk = $query['name']; // как видите, здесь ярлык хранится в другой переменной запроса
  endif;


  $termin = get_term_by('slug', $urlyarlyk, $taxonomia_name); // получаем элемент таксономии по ярлыку

  if (isset($urlyarlyk) && $termin && !is_wp_error($termin)) : // если такого элемента не существует, прекращаем выполнение кода

    // для страниц дочерних элементов код немного отличается
    if ($dochernia) {
      unset($query['attachment']);
      $parent = $termin->parent;
      while ($parent) {
        $parent_term = get_term($parent, $taxonomia_name);
        $urlyarlyk = $parent_term->slug . '/' . $urlyarlyk; // нам нужно получить полный путь, состоящий из ярлыка текущего элемента и всех его родителей
        $parent = $parent_term->parent;
      }
    } else {
      unset($query['name']);
    }

    switch ($taxonomia_name): // параметры запроса для рубрик и меток отличаются от других таксономий
      case 'category': {
          $query['category_name'] = $urlyarlyk;
          break;
        }
      case 'post_tag': {
          $query['tag'] = $urlyarlyk;
          break;
        }
      default: {
          $query[$taxonomia_name] = $urlyarlyk;
          break;
        }
    endswitch;

  endif;

  return $query;
}

// смена самой ссылки
add_filter('term_link', 'true_smena_permalink_3', 10, 3);

function true_smena_permalink_3($url, $term, $taxonomy)
{

  $taxonomia_name = 'service_category'; // название таксономии, тут всё понятно
  $taxonomia_slug = 'service_category'; // ярлык таксономии - зависит от параметра rewrite, указанного при создании и может отличаться от названия,
  // как например таксономия меток это post_tag, а ярлык по умолчанию tag

  // выходим из функции, если указанного ярлыка таксономии нет в URL или если название таксономии не соответствует
  if (strpos($url, $taxonomia_slug) === FALSE || $taxonomy != $taxonomia_name) return $url;

  $url = str_replace('/' . $taxonomia_slug, '', $url); // если мы ещё тут, выполняем замену в URL

  return $url;
}

add_filter('post_link', 'true_post_type_permalink2', 20, 3);
add_filter('post_type_link', 'true_post_type_permalink2', 20, 3);

function true_post_type_permalink2($permalink, $post_id, $leavename)
{

$post_type_name = 'service'; // name of the post type, you can find it in the admin panel or in the register_post_type() function
$post_type_slug = 'service'; // part of the product URL, does not always match the name of the post type!
$tax_name = 'service_category'; // well, this is understandable, the name of the taxonomy is the category of goods

$post = get_post($post_id); // get the post object by its ID

if (strpos($permalink, $post_type_slug) === FALSE || $post->post_type != $post_type_name) // don't make any changes if the post type doesn't match or if the URL doesn't contain a tag tovar
return $permalink;

$termini = wp_get_object_terms($post->ID, $tax_name); // get all categories this product belongs to

if (!is_wp_error($termini) && !empty($termini) && is_object($termini[0])) // and rewrite the link only if the product is at least in one category, otherwise return the default link
$permalink = str_replace($post_type_slug, $termini[0]->slug, $permalink);

return $permalink;
}

add_filter('request', 'true_post_type_request2', 1, 1);

{
global $wpdb; // we have to work with the database a

bit $post_type_name = 'service'; // specify the name of the product record type here
$tax_name = 'service_category'; // as well as the name of the taxonomy - product categories

$yarlik = $query['attachment']; // after we changed the product links in the previous function, WordPress started mistaking them as attachment pages

// now let's get the product ID whose label matches the page query
$post_id = $wpdb->get_var(
"
SELECT ID
FROM $ wpdb->posts
WHERE post_name = '$yarlik'
AND post_type = '$post_type_name'
"
);

$termini = wp_get_object_terms($post_id, $tax_name); // the product must be in a category (one or more)

if (isset($yarlik) && $post_id && !is_wp_error($termini) && !empty($termini)) : // modify the query if everything is OK

unset($query ['attachment']);
$query[$post_type_name] = $yarlik;
$query['post_type'] = $post_type_name;
$query['name'] = $yarlik;

endif;

return $query; // return result
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nastya, 2020-05-02
@Chupizdik

Throw off the code, how you registered an arbitrary service post type and a taxonomy for it service_category

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question