zikoz
zikoz

Reputation: 1

WP Permalinks: display just one kind of wp category in the posts url

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?

Upvotes: 0

Views: 19

Answers (1)

zikoz
zikoz

Reputation: 1

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:

settings

Upvotes: 0

Related Questions