0

I am using WordPress website. Currently Permalink is set up at home/sample-post/ and category is set to "." In present set up my URLs for categories , sub-categories and posts are as follow.

EG Category: Insurance

Sub- Category : Health Insurance , car Insurance

URL Set in Present Permalink Structure:

  1. Category URl: Home/Insurance
  2. Sub-Category : Home/Insurance/health-insurance
  3. Post URL: Home/sample-post/

I want Different URL Structure as follow

  1. Category URL: Home/insurance
  2. Category Post : Home/insurance/sample-post-A

  1. Sub-category URL: Home/health-insurance
  2. Sub-category post : Home/health-insurance/sample-post-B

and so on for other sub categories.

When I set up, /%category%/%postname%/

1st set of desired url is achieved but not holds true for sub-category. Any help would be appreciated. I am new at Wordpress.

1

1 Answer 1

0

You'll need to define your own rewrite tag, and add the tag into the permalink structure.

  • add_rewrite_tag() to register the new structure tag
  • available_permalink_structure_tags filter to add to Permalinks interface
  • post_link filter to change the URL of posts

Below is untested and incomplete code, but should get you pretty far.

add_action( 'init', static function () {
    add_rewite_tag( '%one_category%', '(.+)', 'one_category=' );
} );

add_filter( 'available_permalink_structure_tags', function ( array $tags ) : array {
    $tags['one_category'] = 'Only one category';
    return $tags;
} );

add_filter( 'post_link', static function ( string $permalink, $post ) : string {
    if ( false === stripos( $permalink, '%one_category%' ) ) {
        return $permalink;
    }

    $categories = get_the_category( $post->ID );
    $category = array_pop( $categories );

    return str_replace( '%one_category%', $category->slug, $permalink );
}, 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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