How to Change Post Permalink Programmatically?

WordPress generates URL addresses for all of its content, including posts and pages, using a dynamic permalink system. The permalinks are key component of SEO and UX since it directs visitors to your website.

When you publish a new post or page, WordPress automatically generates a "slug", which is a most important component of the permalink. Typically, the slugs are created from the initial title and converted to make it more readable for search engines and people.

For example, if you title the article "10 Tips for Better Sleep", the slug will be converted to "10-tips-for-better-sleep", resulting in the following URL address:

https://yourwebsite.com/10-tips-for-better-sleep/

Although the slugs are automatically saved, you can still manually adjust them in the content editor before or after the post is published.

SEO Considerations

In terms of your SEO rank, after the post or page is published, it is generally recommended to keep the permalinks consistent. Since search engines may have already indexed your URLs, making changes to them may affect backlinks and result in broken links and lost SEO ranking.

However, there are scenarios in which it still may be advantageous to automatically update the URLs. For instance, if the title of your post contains a year (for instance, "Best Smartphones of 2024"), you might want to have this automatically updated every year in order to make sure that the content remains relevant.

Make sure you do not update your already-indexed permalinks unless you really have to. If you do need to alter them, make sure to properly redirect the old URLs to the new ones in order to maintain your search engine rankings and user experience.

To avoid 404 ("Not Found") error after the permalink is modified, Permalink Manager will automatically redirect the visitors trying to access the old URL to the new address. You can also define additional custom 301 redirects for each post/term using.

Even though WordPress does not have any out-of-box functionality that would allow o automatically update permalinks, you can make it happen with an extra code snippet.

When updating permalinks programmatically in WordPress, the most convenient way is to use the wp_update_post() function.

wp_update_post( array( 'ID' => $post_id, 'post_name' => $new_slug ) );

This core function is designed to update post data, including the post's slug (permalink). You can also use the $wpdb global to run a SQL update query, but this will not trigger any WordPress hooks or filters that would let plugins and themes react to the change.

Below you can find a few snippets that you may use to update the slug or execute extra code when certain post-update conditions are met. These code snippets are basic examples intended to illustrate how permalink updates can be automated.

Please feel free to modify and expand them as needed. Ask an expert WordPress developer for help if you are uncomfortable with PHP, especially while working on a live website.

Changed Post Title

function pm_update_slug_on_title_change( $post_id, $post_after, $post_before ) {
	$post = get_post( $post_id );
	if ( $post_after->post_type == 'post' && $post_after->post_title !== $post_before->post_title ) {
		$new_slug = sanitize_title( $post_after->post_title );
		wp_update_post( array(
			'ID' => $post_id,
			'post_name' => $new_slug
		) );
	}
}
add_action( 'post_updated', 'pm_update_slug_on_title_change', 9, 3 );

Changed Assigned Category

function pm_update_slug_on_term_change( $post_id, $terms, $tt_ids, $taxonomy ) {
	if ( $taxonomy == 'category' ) {
		$new_slug = sanitize_title( $post_after->post_title );
		wp_update_post( array(
			'ID' => $post_id,
			'post_name' => $new_slug
		) );
	}
}
}
add_action( 'set_object_terms', 'pm_update_slug_on_term_change', 9, 4 );

Changed Custom Field Value

function pm_update_slug_on_custom_field_change( $meta_id, $post_id, $meta_key, $meta_value ) {
	if ( $meta_key == 'sample-custom-field' ) {
		$new_slug = sanitize_title( $post_after->post_title );
		wp_update_post( array(
			'ID' => $post_id,
			'post_name' => $new_slug
		) );
	}
}
}
add_action( 'updated_postmeta', 'pm_update_slug_on_custom_field_change', 9, 4 );

Changing permalinks unfortunately involves some risk. A "404" error message indicates that the page is no longer accessible, which can have a detrimental effect on visitors user experience.

To avoid this, before you decide to automatically update permalinks, you should set up a fallback redirect mechanism for old, unused URLs.

The good news is that WordPress's built-in features can manage this to some extent, but there are other options of you would want to have more control over it.

Built-in Fallback Redirect

The most straightforward solution is WordPress' built-in mechanism (wp_old_slug_redirect() function), which monitors slug changes and automatically redirects old URLs to new URLs.

This solution is very basic, but it usually works well enough. When a post's slug changes, WordPress saves the previous slug in the wp_postmeta database table (using the meta key "_wp_old_slug").

When a visitor attempts to access a URL that does not exist, WordPress extracts the slug and looks for a matching "_wp_old_slug" item. If a match is identified, WordPress redirects the visitor to the updated URL.

This functionality is built into WordPress and does not require any further configuration. Unfortunately, it is not perfect. One of the biggest problems is that it only detect the most recent slug's change.

In other words, if a post's slug has been changed multiple times, only the most recent old slug will redirect. Furthermore, it doesn't handle changes to other parts of the URL structure, such as changes in linked categories' slugs.

Custom Redirect Rules

Custom redirect rules may be set up using the .htaccess file (for Apache servers), which is one of the most reliable and traditional methods.

Redirecting via .htaccess tends to be faster than using PHP, though the difference in page speed is usually minimal. However, one downside is that if you need to redirect hundreds or thousands of URLs, the .htaccess file can quickly become cluttered and difficult to manage.

Permalink Manager provides some unique solutions for managing permalink changes and preventing 404 issues. First and foremost, the plugin automatically redirects the native URLs to the new custom permalinks.

Furthermore, using Pro version, you can automatically set-up 301 redirects any time you change a post or term permalink. This feature works similarly to WordPress's built-in solution but offers more extensive coverage:

  • It handles multiple slug changes, not just the most recent one.
  • It can redirect URLs with different permalink structures.
  • It manages redirects for posts, pages, custom post types and taxonomies (categories, tags, etc.).

Redirection Plugin

The Redirection plugin is a very popular and completely free tool allowing to to handle redirects and 404 errors.

Redirection plugin

This plugin provides a user-friendly interface and works on both Apache and NGINX servers. There are so many great functionalities packed into this tool. One of the most useful ones is the automatic tracking of 404 errors, making it easier to spot and fix broken links.

Another useful feature is that it allows to create redirects based on user roles, login status, browser type, and more.

Interestingly, you can use it to import existing redirect rules from your .htaccess file, making migration from server-level redirects to WordPress-managed redirects simple.

by Maciej Bis

Leave a Reply

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