To auto-assign custom page slugs to WordPress pages automatically, you can use the wp_insert_post_data filter to modify the slug before the page is saved to the database. Add the following code snippet to your theme’s functions.php file:
- In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
- In the right sidebar, locate and click on the “functions.php” file.
- Add the following code snippet at the end of the file:
function auto_assign_custom_page_slug($data, $postarr) { // Check if the post is a 'page' post type and if it's a new post being inserted if ($data['post_type'] === 'page' && $postarr['ID'] === 0) { // Create a custom slug based on the current date and time // You can modify this to create a custom slug according to your requirements $custom_slug = 'page-' . date('Ymd-His'); // Assign the custom slug to the post $data['post_name'] = sanitize_title($custom_slug); } return $data; } add_filter('wp_insert_post_data', 'auto_assign_custom_page_slug', 10, 2);
This code snippet creates a function called auto_assign_custom_page_slug() that checks if the post is a new page, and if so, it generates a custom slug based on the current date and time. You can modify the $custom_slug variable to create a custom slug according to your requirements.
- Click “Update File” to save the changes.
Now, when you create a new page in WordPress, a custom slug will be automatically assigned to it.
Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.