A
A
Andrey2019-01-07 19:13:57
WordPress
Andrey, 2019-01-07 19:13:57

Show only one category in wordpress cnc?

For posts from the standard Blog category, it was necessary to use CNC with the category - site.com/blog/post-title. In general, the following CNC structure on the site is site.com/post-title. The task was implemented by the following code in function.php

add_action('init', function()
{
    add_rewrite_rule('^blog/([^/]+)/?$', 'index.php?name=$matches[1]', 'top');
}, 10, 0);
add_filter('post_link', function($post_link, $post, $leave_name = false, $sample = false)
{
    if ( has_category('blog', $post) ) {
        $post_link = str_replace('/' . $post->post_name, '/blog/' . $post->post_name, $post_link);
    }

    return $post_link;

}, 10, 4);

Everything works well, but there is one problem. If you use the link site.com/post-title (instead of site.com/blog/post-title), then the post is displayed without /blog/, but I would like a redirect to site.com/blog/post-title. Can you tell me how to implement a redirect in the code?

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