Forum Replies Created

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter hombero

    (@hombero)

    The issue was indeed due to a missing include that a function inside of media_handle_sideload!

    Including the files that pandymic mentioned solved the issue.

    Thank you very much to everybody for their help!

    Thread Starter hombero

    (@hombero)

    Hello, thank you for your reply. I should have mentioned in the original post that $debug is a variable I have defined at the beginning of this script as True to echo debugging information. I did not have WP_DEBUG turned on but I have since turned it on at the top of the script as well.

    I’ve incorporated the is_wp_error($id) check as you have suggested, though the script seems to halt at the media_handle_sideload() call so it never prints the error message.

    This is what I have now:

    function wp_sideload_image($post_id, $file, $desc = null)
    {	
    
    	global $debug; // defined outside of function as True
    
    	if ( ! empty($file) ) {
    		if ($debug) { echo 'File not empty <br />'; }
    		// Download file to temp location
    		$tmp = download_url( $file );
    		// Set variables for storage
    		// fix file filename for query strings
    		preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $file, $matches);
    		$file_array['name'] = basename($matches[0]);
    		$file_array['tmp_name'] = $tmp;
    
    		// If error storing temporarily, unlink
    		if ( is_wp_error( $tmp ) ) {
    			@unlink($file_array['tmp_name']);
    			$file_array['tmp_name'] ='';
    			if ($debug) { echo 'Error storing temp file! <br />'; }
    		}
    
    		// do the validation and storage stuff
    		if ($debug) { echo 'File array: <br />';
    			var_dump($file_array);
    			echo '<br /> Post id: ' . $post_id . '<br />';
    		}
    
    		$id = media_handle_sideload( $file_array, $post_id, $desc );
    
    		// check for error in $id
    		if ( is_wp_error($id) ) {
    			@unlink($file_array['tmp_name']);
    			var_dump( $id->get_error_messages( ) );
    		}
    		else {
    			add_post_meta($post_id, '_thumbnail_id', $id, true);
    		}
    	}
    }

    It produces this output:

    File not empty
    File array:
    array(2) { [“name”]=> string(6) “16.png” [“tmp_name”]=> string(12) “/tmp/161.tmp” }
    Post id: 1160

    I’m not sure what I’m doing wrong, I’ve read the media_handle_sideload() docs and it seems that this is what the function expects as parameters along with the description.

    Please help and thank you again!

    Thread Starter hombero

    (@hombero)

    Thanks a lot!

Viewing 3 replies - 1 through 3 (of 3 total)