Bulk rewrite post slugs based on custom field value in Wordpress
1) Create a new page and assign a new page template to it, lets say site.com/update
and update.php
. Inside of update.php write you bulk mechanism:
<?php // grab all your posts$parts = get_posts(array('post_type' => 'parts', 'numberposts' => -1,))// loop through every partforeach ( $parts as $part ) { // get part number $partno = get_post_meta( $part->ID, 'parto', true ); $updated_post = array(); $updated_post['ID'] = $part->ID; $updated_post['post_name'] = $partno; wp_update_post( $updated_post ); // update existing posts} ?>
You could place this anywhere in your theme but I like to create a page for that so I can easily run a cron job with it.
Next the function to change the slug of every newly created post:
<?php function change_default_slug($id) { // get part number $partno = get_post_meta( $id, 'parto', true ); $post_to_update = get_post( $id ); // prevent empty slug, running at every post_type and infinite loop if ( $partno == '' || $post_to_update['post_type'] != 'parts' || $post_to_update['post_name'] == $partno ) return; $updated_post = array(); $updated_post['ID'] = $id; $updated_post['post_name'] = $partno; wp_update_post( $updated_post ); // update newly created post}add_action('save_post', 'change_default_slug'); ?>
The code above runs every time a post gets saved (e.g. when published for the first time) and sets a new post_name to the part no.