Add more structure tag to permalink?

I’m new in wordpress .I wondering is there anyway to get the category id in permalink ?
My current permalink is :

http:///example.com/%category%/%post_id%-%postname%.html
http:///example.com/music/1-hello.html

Now my music category_id is 2 , how to add this category_id to permalink ? I want to this:

http:///example.com/2-music/1-hello.html

Related posts

Leave a Reply

1 comment

  1. You would have to create your own permalink structure tab. For example:

    add_filter('post_link', 'cat_id_permalink', 10, 3);
    add_filter('post_type_link', 'cat_id_permalink', 10, 3);
    
    function cat_id_permalink($permalink, $post_id, $leavename) {
        if (strpos($permalink, '%catid%') === FALSE) return $permalink;
    
        // Get post
        $post = get_post($post_id);
        if (!$post) return $permalink;
    
        // Get category ID
        $category = end(get_the_category());
        $catid = $category->cat_ID;
    
        return str_replace('%catid%', $catid, $permalink);
    }
    

    Note, this code will only work if the post is listed in one category. You’ll have to add a bit more logic if the post is possibly listed under more than one category.

    This code is added to your functions.php file. WordPress filters allow you to modify or extend the functionality of the core WordPress code without having to change the core files (and risk losing your changes with the next WordPress update.)

    The code above is called prior to returning a processed url (via the post_link and post_type_link filters). When the function runs, it returns the newly parsed permalink structure.

    The // Get post code returns the original permalink unchanged is there isn’t a valid post ID.

    The // Get category ID uses get_the_category() to retrieve a category ID if there is a valid post ID. Note get_the_category() retrieves an array of category IDs, because a post may be in multiple categories. The end function returns the last element of the array.

    Finally, using str_replace, we swap our the %catid% tab with the $catid variable, and return the new permalink.