1

I am using 2 different categories in my site /blog/ and /news/. I want to display the /news/ category in my posts but I don't want to display the /blog/ category in the url of the blog posts. I already have a lot of posts and different templates for each category so I would like to avoid to create pages to do this. The idea is the following:

/news/ category --> index.php/news/post-name/

/blog/ category --> index.php/post-name/

Is this possible?

1 Answer 1

0

Two things need to be done. First, make your posts URL is different using the post_link filter.

function _20170117_post_link( $url, $post, $leavename ) {
    if( in_category( 'news', $post) ) { 

        $url = get_site_url() . '/news/' . $post->post_name ;
    }
    return $url;
}
add_filter( 'post_link', '_20170117_post_link', 10, 3 );

Second, make the rewrite rule for this:

function _20170117_rewrite() {
  add_rewrite_rule('^news/(.?.+?)(?:/([0-9]+))?/?$', 'index.php?pagename=$matches[1]
&page=$matches[2]', 'top');
  add_rewrite_rule('^news/([^/]+)(?:/([0-9]+))?/?$', 'index.php?name=$matches[1]
&page=$matches[2]', 'top');
  flush_rewrite_rules();
}
add_action('init', '_20170117_rewrite');

Note that flush_rewrite_rules(); you don't need to execute every time. Just once. Or you may goto options-permalink.php and click Save.

I tested with the following settings:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.