Skip to content

How To Set WordPress Permalinks From functions.php

Permalinks are the permanent URLs to your WordPress or blog posts, as well as pages and other things on your WordPress blog or any other website. It’s very important to have an easy permalink structure for your URLs for better navigation and SEO. The default WordPress permalinks looks like this:

https://www.example.com/?p=22

You can easily change the structure of your permalinks in the settings of your WordPress but you can also change the structure from your theme’s functions.php file.

Add the following code snippet to your website (or directly in the functions.php file):

// set permalink
function set_permalink(){
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%postname%/');
}
add_action('init', 'set_permalink');Code language: PHP (php)

You can change the structure of your permalinks with following structure codes:

 %year%
    The year of the post, four digits, for example 2004

 %monthnum%
    Month of the year, for example 05

 %day%
    Day of the month, for example 28

 %hour%
    Hour of the day, for example 15

 %minute%
    Minute of the hour, for example 43

 %second%
    Second of the minute, for example 33

 %post_id%
    The unique ID # of the post, for example 423

 %postname%
    A sanitized version of the title of the post (post slug field on Edit Post/Page panel). So “This Is A Great Post!” becomes this-is-a-great-post in the URI.

 %category%
    A sanitized version of the category name (category slug field on New/Edit Category panel). Nested sub-categories appear as nested directories in the URI.

 %author%
    A sanitized version of the author name.

Leave a Reply

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