I have a script that uploads each file in a specific directory to my WordPress site. Right now, the script only uploads one image, the last image in the directory. I believe my problem is in the for loop that is assigning the uploaded files name. Here is my code:
function vehicle_image_uploads() {
?>
<button id="veh_img_upload">Upload Images</button>
<?php
global $post;
$rpcurl = get_bloginfo('url') . "/xmlrpc.php";
echo $rpcurl;
$username = 'admin';
$password = 'admin';
$blogid = $post->ID; //Post ID
echo $blogid;
$post_idn = get_post_meta($post->ID, 'VIN', true);
echo "<h1>" . $post_idn ."</h1>";
$post_dir = dirname( get_template_directory() ) . "/" . $post_idn;
$fileslist = scandir($post_dir);
foreach ($fileslist as $file) {
echo $file;
}
$i = 0;
foreach ($fileslist as $file) {
if( $file === '.' || $file === '..' ) {
continue;
}
$file = file_get_contents( $post_dir . "/" . $file);
$filetype = "image/jpeg";
$filename = "remote_filename_". $i .".jpg";
$i++; //
xmlrpc_set_type($file,'base64'); // <-- required!
$params = array($blogid,$username,$password,
array('name'=>$filename,'type'=>$filetype,'bits'=>$file,'overwrite'=>false));
$request = xmlrpc_encode_request('wp.uploadFile',$params);
echo "<br />" . $filename;
}
function go($request,$rpcurl){
$ch = curl_init();
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_URL,$rpcurl);
curl_setopt($ch,CURLOPT_POSTFIELDS,$request );
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
}
$result = go($request,$rpcurl);
print_r($result);
}
What I am wanting to do is name each upload file "remote_filename" with _1, _2, _3 etc. etc. added to the end of each file.
+1 to using external iterator, and also:
Where is the actual RPC taking place? Can you extend your code snippet to show that?
Maybe you call it just once already oustide of the foreach
loop like this:
foreach ($fileslist as $file) {
//...
$request = xmlrpc_encode_request('wp.uploadFile',$params);
}
$file = file_get_contents($rpcurl, ...); //or however you call it
It would produce the effect, you're experiencing - no matter what uploading only one file (the last one you processed from the list).
It should be called inside the loop, for every file.