Move wordpress media files based on mysql column (reorganize based on date)

I have a wordpress site where the user opted to not organize media by date. NOW, 2000 or so images later, they want it organized by date.

I have put together my query to change my urls based on the date of the parent post.

Read More

However, now I have to set about actually moving the images to their new homes.

I started a php script to attempt to move files based on the date of the parent post they are attached to.

$wp_path = getenv('ACT_PATH');
if(is_null($wp_path) || empty($wp_path)) {
        echo('ERROR: Environment variable $ACT_PATH must be defined'. "n");
        exit(10); 
} 
require_once($wp_path . 'wp-load.php'); 
require_once($wp_path . 'wp-includes/post.php'); 
$query = array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'any',
        'post_parent' => null 
); 
$attachments = get_posts($query);
/**  
* Inserts year and month components to the provided array of guid parts 
* @param array $bits Parts of a file guid to be modified  
* @param int $year Year to insert into file guid  
* @param int $month month to insert into file guid  
*/ function addDateParts(&$bits, $year, $month) {
        $base_index = array_search('uploads', $bits);
        if($base_index !== false) {
            $suffix = $bits[$base_index + 1];
            $bits[$base_index + 1] = $year;
            $bits[$base_index + 2] = $month;
            $bits[$base_index + 3] = $suffix;
        }
  } 
echo('Source,Upload Date,Destination'. "n"); foreach ($attachments as $a) {
        $time = strtotime($a->post_date_gmt);
        $year = date("Y", $time);
        $month = date("m", $time);
        $guid_bits = explode('/', $a->guid);
        addDateParts($guid_bits, $year, $month);
        $new_guid = implode('/', $guid_bits);
        echo($a->guid . ',' . $a->post_date_gmt . ',' . $new_guid . "n"); 
}

But I find myself somewhat stuck on what to do next. Any help is appreciated.

Related posts

Leave a Reply