/**
* Делаем ссылки вида: /%category%/%post_tag%/%postname%/ + настраиваем пагинацию
*/
function flush_rewrite_rules_on_activation() {
flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'flush_rewrite_rules_on_activation' );
function custom_rewrite_tag() {
add_rewrite_tag('%tag%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);
function custom_rewrite_rules() {
add_rewrite_rule('^(news||faq||actions)/page/([0-9]+)/?', 'index.php?category_name=$matches[1]&paged=$matches[2]', 'top');
add_rewrite_rule('^(news||faq||actions)/([^/]*)/page/([0-9]+)/?', 'index.php?category_name=$matches[1]&tag=$matches[2]&paged=$matches[3]', 'top');
add_rewrite_rule('^(news||faq||actions)/([^/]*)/([^/]*)/?', 'index.php?category_name=$matches[1]&tag=$matches[2]&name=$matches[3]', 'top');
}
add_action('init', 'custom_rewrite_rules');
function custom_query_vars($query_vars) {
$query_vars[] = 'tag';
return $query_vars;
}
add_filter('query_vars', 'custom_query_vars');
function custom_parse_request($query) {
if (!empty($query->query_vars['tag']) && !empty($query->query_vars['category_name'])) {
$post_tag = $query->query_vars['tag'];
$category = $query->query_vars['category_name'];
$term = get_term_by('slug', $post_tag, 'post_tag');
if (!$term && $post_tag !== 'page' && $post_tag !== 'all') {
global $wp_query;
$wp_query->set_404();
status_header(404);
get_template_part(404);
exit();
}
$args = array(
'category_name' => $category,
'tag' => $post_tag,
'post_type' => 'post',
'posts_per_page' => 1
);
$posts = get_posts($args);
if (empty($posts) && $post_tag !== 'page' && $post_tag !== 'all') {
global $wp_query;
$wp_query->set_404();
status_header(404);
get_template_part(404);
exit();
}
}
}
add_action('parse_request', 'custom_parse_request', 10, 1);
/**
* Редактируем ссылки на постах
*/
function custom_permalink_structure($permalink, $post, $leavename) {
if (strpos($permalink, '%tag%') === FALSE) return $permalink;
// Получаем теги поста
$tags = get_the_terms($post, 'post_tag');
if (!is_wp_error($tags) && !empty($tags) && is_object($tags[0])) {
$tag_slug = $tags[0]->slug;
} else {
$tag_slug = 'all';
}
$permalink = str_replace('%tag%', $tag_slug, $permalink);
return $permalink;
}
add_filter('post_link', 'custom_permalink_structure', 10, 3);
add_filter('post_type_link', 'custom_permalink_structure', 10, 3);