Skip to content

Instantly share code, notes, and snippets.

@glueckpress
Last active April 28, 2019 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glueckpress/5013923 to your computer and use it in GitHub Desktop.
Save glueckpress/5013923 to your computer and use it in GitHub Desktop.
[WordPress] Page template to bulk update page slugs with a given name scheme. USE WITH CAUTION! To avoid accidental re-slugging of pages, there’s $update_slugs_now set to false by default.
<?php
/*
Template Name: CAUTION - Bulk Update Page Slugs
SECURITY FEATURE: Will only update pages with a given author!
1. Create a new user with username "bulkupdater".
2. Assign all pages you need to update to author bulkupdater.
3. Create a new page, assign this template and open it in the browser.
4. You'll see a preview of what's going to happen.
5. Set $update_slugs_now to true and relaod the page in your browser to perform the update.
Based upon a solution by Jan Beck: http://stackoverflow.com/a/11751432
*/
// Set this to true to perform the update. Have you checked the name scheme in line 39?
$update_slugs_now = false;
// Query pages
$pages = get_posts( array(
'post_type' => 'page',
'posts_per_page' => -1,
'author_name' => 'bulkupdater'
) );
// Stop if query is empty.
if( empty( $pages ) ) :
echo 'Nothing to update';
exit;
endif;
// Info message
echo ( true == $update_slugs_now ) ? '<p><strong>Update performed!</strong</p>' : '<p><strong>This is a preview. Go for it? Set <code>$update_slugs_now</code> to <code>true</code> and reload this page.</strong></p>';
// Set a counter
$i = 1;
// Loop through queried pages
foreach ( $pages as $page ) :
// Store for later
$old = $page->post_name;
// Define your name scheme here!
// The below scheme results in URLs like:
// http://example.com/mypage-updated-1
$post_name = sprintf( '%1$s-%2$s-%3$s',
$old, // the old page slug
'updated', // a custom text string
$i // the counter
);
$new = array();
$new['ID'] = $page->ID;
$new['post_name'] = $post_name;
$updated = 'Going to update';
// Update existing posts
if( true == $update_slugs_now ) :
$updated = 'Updated';
wp_update_post( $new );
endif;
printf( '%1$s <em>%2$s</em> to <strong>%3$s</strong>.<br />', $updated, $old, $new['post_name'] );
// Update counter
$i++;
endforeach;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment