PHP Web Development Wordpress

Update post slug as per post name

 function nis_update_post_slug($postType){
  $log_arr = array();
  // get posts
  $posts = get_posts( array ('numberposts'=> -1,'post_type'=>$postType) );
  // set process start time
  $log_arr[] = "\n Update started at ". date('Y-m-d H-i-s',time());
  foreach ( $posts as $post ):
    $old_slug = $post->post_name;
    // check the slug and run an update if necessary 
    if(!in_array( $post->status, array( 'draft', 'pending', 'auto-draft' ) ) ){
      if($post->post_title!=''){
        $new_slug = wp_unique_post_slug(sanitize_title($post->post_title),
                                      $post->ID,
                                      $post->status,
                                      $post->post_type,
                                      $post->post_parent
                                    );
        /// update only when old slug is different from new slug
        if($new_slug!=$old_slug){
          wp_update_post( array ('ID'=>$post->ID,'post_name'=>$new_slug) );
          $log_arr[]="\nTitle: ".$post->post_title." ,Old slug: $old_slug ,New Slug: $new_slug";  
        }
      }
    }
    
  endforeach;
  $log_arr[] = "\n Update finished at ". date('Y-m-d H-i-s',time());
/// put update in log file
  file_put_contents(ABSPATH.'/wp-content/uploads/wc-logs/slug-update.log', $log_arr, FILE_APPEND | LOCK_EX);  
}

Leave a Reply

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


CAPTCHA Image
Reload Image