How to change the post slug with WordPresss functions?
How to change the post slug with WordPresss functions?
After a post is created, it looks like:
https://www.example.com/mypost/
Now I want to use a WordPress built-in function to change 'mypost' to 'yourpost'. How to do so? I cannot find such a function on Google
To change the slug in WordPress, you can use the wp_update_post function along with the wp_insert_post function. Here's how you can do it:
<?php
// First, get the post ID based on the post URL
$post_url = 'https://www.example.com/mypost/';
$post_id = url_to_postid( $post_url );
// If post ID is found
if ( $post_id ) {
// Get the post object
$post = get_post( $post_id );
// Update the post's slug to 'yourpost'
$post->post_name = 'yourpost';
// Update the post in the database
wp_update_post( $post );
echo "Slug updated successfully!";
} else {
echo "Post not found!";
}
?>
Hopefully this will fix your problem. Happy Coding :)
February 13, 2024
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand
February 13, 2024