M
M
makaravich2021-05-24 11:32:50
PHP
makaravich, 2021-05-24 11:32:50

How to set URL rewriting rules?

Somehow it so happened that I'm not strong in regular expressions, as well as in creating CNC (human-readable URLs for WordPress) :-)

Actually the problem:

In WordPress, in the theme we use, there is a custom post type tovar. By default, this post type has a URL structure:

https://oursite.ru/catalog/%tovar_category%/%tovar_name%

where:
%tovar_category%- product category slug - product
%tovar_name%slug It is

required to make a URL like:
https://oursite.ru/%city%/%tovar_name%
where:
%city%- city name (can change dynamically, can be obtained through the corresponding function)
%tovar_name%- product slug

To solve the problem, when registering this custom post type, I try to set the slug
'slug' => '%city%'

and rewrite the value of the variable %city%with the following code:

function show_city_permalinks( $post_link, $post ) {
  if ( is_object( $post ) && $post->post_type == 'tovar' ) {
    return str_replace( '%city%', strtolower( IC_Geo::sc_current_city_lat() ), $post_link );
  }

  return $post_link;

}
add_filter( 'post_type_link', 'show_city_permalinks', 1, 2 );


At the same time, for some reason, the URLs of ordinary pages (page) break.

But if you set it
'slug' => 'city/%city%'
(by adding another city element to the URL ), then everything works fine.

The problem is that we don't need this element.

How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question