How to Set Permalink Settings from Functions.php in WordPress

Home » Snippets » How to Set Permalink Settings from Functions.php in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you interested in altering the default structure of your WordPress permalinks? Modifying permalink settings can significantly improve your website’s SEO performance and user experience. The ‘functions.php’ file, a crucial component of your WordPress theme, can facilitate this modification. This article is a step-by-step guide on how to accurately adjust your permalink settings directly from ‘functions.php’ and streamline your website addresses to your preference.

					function wpturbo_set_permalink() {
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure('/%postname%/');
}
add_action('init', 'wpturbo_set_permalink');
				

The first line of the code snippet presents a function, wpturbo_set_permalink(). This function is created to set the permalink structure of your WordPress site. The permalink structure is the format that WordPress uses for the URLs of posts and pages on your site.

In the function, we first call the global $wp_rewrite object, which handles all different rewrite rules for WordPress. By making it global, we can access the properties and methods of this object within our function.

Next, the method set_permalink_structure() is called on the $wp_rewrite object:

$wp_rewrite->set_permalink_structure('/%postname%/');

This method is used to set the permalink structure for your WordPress site. In the brackets, you will see '/ %postname%/ ', which is the structure that we want to set.

The '%postname%' placeholder is a WordPress structure tag – it is replaced by WordPress with the post name. The format '/ %postname%/ ' ensures that the title of every post or page will be part of the URL.

For instance, if we have a post named "Hello World", its URL will be "www.yoursite.com/hello-world".

Finally, the add_action() function is used to attach our wpturbo_set_permalink() function to the ‘init’ hook:

add_action('init', 'wpturbo_set_permalink');

The ‘init’ hook is run after WordPress has finished loading, but before any headers are sent – making it an ideal spot to change the permalink structure. Here, by adding our function to this hook, we ensure the permalink structure is set as soon as WordPress loads, ensuring the URLs of posts and pages will be in the desired format.

Register an account to save your snippets or go Pro to get more features.