Last updated on September 13, 2023

Custom Permalink Structure

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Create a custom permalink structure.

Custom permalink structures in WordPress allow you to define a custom URL structure for any post type or taxonomy on your site. This can be useful for creating more user-friendly URLs or for optimizing your site’s SEO. Here’s an example code snippet to create custom permalink structures in WordPress:

function wpsnippets_custom_permalinks() {
    // Define custom permalink structure for custom post type
    global $wp_rewrite;

    $wp_rewrite->add_permastruct( 'custom-post-type', '/%category%/%postname%/', true );

    // Define custom permalink structure for custom taxonomy
    $wp_rewrite->add_rewrite_tag( '%custom-taxonomy%', '([^/]+)', 'custom-taxonomy=' );
    $wp_rewrite->add_permastruct( 'custom-taxonomy', '/%custom-taxonomy%/%postname%/', true );
}

add_action( 'init', 'wpsnippets_custom_permalinks' );

In this code snippet, we define a function wpsnippets_custom_permalinks() that sets a custom permalink structure for a custom post type in WordPress and a custom taxonomy using the $wp_rewrite global variable. For the custom post type, we define the permalink structure to include both the post category and post name, separated by a forward slash, using the add_permastruct() method. We set the third parameter to true to ensure that the permalink structure is hierarchical, meaning that it includes parent categories in the URL.

For the custom taxonomy, we define a rewrite tag using the add_rewrite_tag() method to capture the name of the custom taxonomy in the URL. We then use the add_permastruct() method to define the custom permalink structure to include the custom taxonomy name and the post name, separated by a forward slash. We also set the third parameter to true to make the permalink structure hierarchical.

Make sure to flush your rewrite rules after adding the code above. This can be done by going to Settings -> Permalinks and just clicking Save Changes. It’s not recommended to do this programatically on every page load using $wp_rewrite->flush_rules() or flush_rewrite_rules(), because it is bad practice and it will slow down your site.

With this code in place, the custom WordPress permalink structure for the custom post type and custom taxonomy will include the category or taxonomy name and the post name, separated by a forward slash. Note that you can customize the permalink structure for any post type or taxonomy by modifying the arguments passed to the add_permastruct and add_rewrite_tag() methods.

Last updated on September 13, 2023. Originally posted on May 12, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *