I am trying to receive files from a webservice and save them into wordpress but I have following issues,
- Some of the files will be uploaded but they are corrupted and I can’t open them, although their webservice address is correct.
- It shows the following errors (although it shows these errors but upload the files anyway, which is good 😀 but I am wondering why I am receiving them).
Notice: Constant ABSPATH already defined in /Applications/MAMP/htdocs/wordpress/wp-load.php on line 22
Fatal error: Call to undefined function wp_generate_attachment_metadata() in /Applications/MAMP/htdocs/wordpress/wp-content/plugins/myproject/Myclasses/retrieve_2334.php on line 95
My Code:
ini_set( 'display_errors', TRUE );
error_reporting( E_ALL );
require("/Applications/MAMP/htdocs/wordpress/wp-load.php");
$pos = strrpos($Address, "&f=");
$loc = substr($Address, $pos + 3);
$Address = "http://dev.piction.com/v60/" . $Address;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, $Address);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$upload_dir = wp_upload_dir();
$location= $upload_dir['basedir']. "/" . $loc;
try{
$location= $upload_dir['path']. "/" . $loc;
$wp_filetype = wp_check_filetype($loc, null );
$fullpathfilename = $upload_dir['path'] . "/" . $loc;
$fileSaved = file_put_contents($location, $output);
if ( !$fileSaved ) {
throw new Exception("The file cannot be saved.");
}
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/.[^.]+$/', '', $loc),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $upload_dir['url'] . "/" . $loc
);
$attach_id = wp_insert_attachment( $attachment, $fullpathfilename, 0 );
if ( !$attach_id ) {
throw new Exception("Failed to save record into database.");
}
//require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullpathfilename );
wp_update_attachment_metadata( $attach_id, $attach_data );
} catch (Exception $e) {
$error = '<div id="message" class="error"><p>' . $e->getMessage() . '</p></div>';
}
echo 'Photo is uploaded';
It does seem as if you’re including a file twice, that would explain why you’re getting the “already defined” errors.
Try removing the
require()
statement in the third line of your code and see if it works, as it seems as if that file is already being included somewhere else in your script.Try changing to
require_once("/Applications/MAMP/htdocs/wordpress/wp-load.php");
as you get the already defined notice it might indicate you have already included wp-load.php.Also you need to uncomment the line
//require ( ABSPATH . 'wp-admin/includes/image.php' );
to be able to usewp_generate_attachment_metadata()