Uncaught Error: Call to undefined function wp_generate_attachment_metadata() @ wp-cron

Devs

I have a WP-cronjob running that is supposed to import some pictures and set them as attachments for a specific post. But I’m apparently unable to do so while running it as a WP-cronjob – it works just fine when i run it on “init” for exampel. But as soon as i try to run it within a WP-cronjob it fails.

 register_activation_hook( __FILE__, 'OA_FeedManager_activated' );
 function importpicture_activated()
 {
    if (! wp_next_scheduled( 'import_feed' ) ) 
    {
       wp_schedule_event( time(), 'hourly', 'import' );
    }
 }

  add_action( 'import', 'call_import' );
  function call_import() 
  {
        //lots of code, where i get data from a XML feed, and creates a new post. no need to include it.           

        foreach($oDataXML->Media->Fotos->Foto as $key => $value)
        {
            $filename = wp_upload_dir()['path']."https://wordpress.stackexchange.com/".$oDataXML->SagsNr->__toString().'_'. $value->Checksum->__toString() . '.jpg';  
            $sPicture = $value->URL->__toString();
            copy($sPicture, $filename);
            $filetype = wp_check_filetype( basename( $filename ), null );

            $wp_upload_dir = wp_upload_dir();
            $attachment = array(
               'guid'           => $wp_upload_dir['url'] . "https://wordpress.stackexchange.com/" . basename( $filename ),
               'post_mime_type' => $filetype['type'],
               'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
               'post_content'   => '',
               'post_status'    => 'inherit'
            );
            $attach_id = wp_insert_attachment( $attachment, $filename, $iPost_ID );
            $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
            wp_update_attachment_metadata( $attach_id, $attach_data );           
        }
  } 

As I have been able to read, its because that the wp_generate_attachment_metadata() function is not currently included when doing a wp-cronjob, and I should require_once('wp-load.php').

But sadly I’m not able to require that while running a cron job (I tried both wp-load.php & wp-includes/post.php) – but neither does the trick.

So maybe there is a wise man on WPSE that can enlighten me how I’m suppose to get my WP-cronjob running correctly.

2 s
2

Some of what is usually admin side functionality is not included as part of the “main” wordpress bootstrap, files containing uploaded file manipulation functions are one of them and you need to explicitly include them by adding

include_once( ABSPATH . 'wp-admin/includes/image.php' );

into your call_import function.

Leave a Comment