Skip to main content
1 of 2
vexx
  • 11
  • 3

Custom permalink structure for posts in certain categories

As the title says, I want to create a different permalink structure for posts belonging to a certain category, in my case, the name is "ICO". I've found this piece of code on StackExchange, but it doesn't really do anything for me, contrary to the OPs feedback.

The code is:

//Rewrite URLs for "ICO" category
add_filter( 'post_link', 'custom_permalink', 10, 3 );

function custom_permalink( $permalink, $post, $leavename ) {
// Get the category for the post
$category = get_the_category($post->ID);
if (  !empty($category) && $category[0]->cat_name == "ICO" ) {
    $cat_name = strtolower($category[0]->cat_name);
    $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) );
}
return $permalink;
}

add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
    'ico/([^/]+)(?:/([0-9]+))?/?$',
    'index.php?category_name=ico&name=$matches[1]&page=$matches[2]',
    'top' // The rule position; either 'top' or 'bottom' (default).
);
}

All posts from that category, present on the homepage do not have their URL changed, the default URL structure is the same www.site.com/post_name/

However, I noticed that on some widgets, in a list with posts from that category, some of the posts have their URL changed, some do not. There isn't any difference between them, they have the same categories. Even if I go on that URL /ico/post_name/ it works and if I delete /ico/ and go on the default permalink structure, it works as well, making it a duplicate URL for the same post.

What have I done wrong?

vexx
  • 11
  • 3