Function Friday #8: add the blog page slug to single post permalinks

Function Friday #8

Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.


If a site is using WordPress posts for non-time-sensitive content (like this one), I’ll often remove the date from the permalinks by changing the permalink settings (Settings → Permalinks) to “Post name” instead of “Day and name”:

Post name permalinks setting

On a site that’s using a Posts Page (again, like this site – my posts are on the Writing page instead of my homepage) I’ll also add the slug from the Posts Page into the URL of all posts, plus all category and tag archives. It’s a small detail that makes finding your way around the site just a little bit easier.

Without the slug:

With the slug:

This can all be done by simply changing settings (no code necessary!). While I was at it, I also changed “category” in the URL for category archives to “topic”, and “tag” to “style”:

Custom permalink settings

Where you might need some code is once you add a custom post type or two.

The code

// Register custom post type
function drollic_create_post_type() {
    register_post_type( 'work',
        array(
            'public' => true,
            'rewrite' => array(
                'with_front' => false
            ),
        )
    );
}
add_action( 'init', 'drollic_create_post_type' );

// Register custom taxonomy
function drollic_create_taxonomy() {
    register_taxonomy(
        'types',
        'work',
        array(
            'public' => true,
            'rewrite' => array(
                'with_front' => false
            )
        )
    );
}
add_action( 'init', 'drollic_create_taxonomy' );

Normally you’d include more arguments in the register_post_type and register_taxonomy functions, but 'with_front' => false is the relevant one here. Setting it to false means the “work” post type and the “types” taxonomy won’t have “writing” (or whatever you put in the permalink settings field above) in their URLs.

'with_front' => true (the default if not set explicitly):

'with_front' => false:

Where does it go?

If you’re creating a custom post type or taxonomy, the code for that would go in your theme’s functions file. More thoughts on code location are in the first post in the Function Friday series.

Resources

Leave a Reply

Your email address will not be published.