[Plugin: Duplicate Post] Duplicate Attachments
-
If you wish to duplicate all of the attachments of a post/page as well, add the following code to your themes function.php file. Most won’t have a use for this, but I had a site that embeded uploaded images dynamically and needed to be duplicated into other areas.
function dupeAttachments($pID, $oldpost){ global $wpdb; //1. get old attachments $attachments = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = $oldpost->ID AND post_type = 'attachment'"); //2. duplicate old attachments data foreach($attachments as $att): $wpdb->query("INSERT INTO $wpdb->posts (post_title) VALUES ('')"); $newID = $wpdb->insert_id; $IDs[] = array( 'old' => $att->ID, 'new' => $newID ); $query = "UPDATE $wpdb->posts SET "; foreach( $att as $key=>$val ){ if( $key == 'post_name'): $query .= '<code>'.$key.'</code> = "'.str_replace('"','\"',$val).'-2", '; elseif( $key == 'post_parent' ): $query .= '<code>'.$key.'</code> = "'.$pID.'", '; elseif ($key != 'ID'): $query .= '<code>'.$key.'</code> = "'.str_replace('"','\"',$val).'", '; endif; } $query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma $query .= " WHERE ID=$newID"; if( $wpdb->query($query) ){}else{echo $query; exit;} $query = false; endforeach; // duplicate attachment meta data foreach($IDs as $id): $meta = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE post_id = ".$id['old']); foreach( $meta as $mt ){ $query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) VALUES ('".$id['new']."', '".$mt->meta_key."', '".str_replace("'","\'",$mt->meta_value)."')"; if( $wpdb->query($query) ){}else{echo $query;exit;} $query = false; } endforeach; } add_action("dp_duplicate_post", "dupeAttachments", 1, 2); add_action("dp_duplicate_page", "dupeAttachments", 1, 2);
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘[Plugin: Duplicate Post] Duplicate Attachments’ is closed to new replies.