9

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'].'/'.$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'] . '/' . 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 Answers 2

15

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.

2
  • @Fayaz, sorry for taking rep from you, was just easier to answer than to comment ;) Commented Mar 24, 2017 at 15:46
  • I wanted to delete my answer (after yours), but it has part of the solution as well, So I updated it instead :)
    – Fayaz
    Commented Mar 26, 2017 at 9:45
2

At the top of your cronjob script (for example: my-cron.php), do this:

if ( ! defined('ABSPATH') ) {
    /** Set up WordPress environment */
    require_once( dirname( __FILE__ ) . '/wp-load.php' );
}

Then setup cron like this in your server:

5 * * * * wget -q -O - http://your-domain.com/my-cron.php

Note: perhaps you were trying to run cron as PHP Command Line (CLI), that'll not work. You need to run cron as HTTP request (with wget or curl), as shown above.

For more information read this official WordPress document.

Update:

Based on newly added CODE, I can see this CODE is wrong:

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
 }

You checked if ( ! wp_next_scheduled( 'import_feed' ) ) but you are scheduling add_action( 'import', 'call_import' );. For cron to work properly you must register the same action import. Also, your activation hook is OA_FeedManager_activated, make sure it runs importpicture_activated function. So the CODE should be like:

register_activation_hook( __FILE__, 'OA_FeedManager_activated' );

function OA_FeedManager_activated() {
    importpicture_activated();
}

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

 add_action( 'import', 'call_import' );
 function call_import() {
     // lots of code
 }

To check if your cron is registered properly, you may use the control plugin. Also, activate WP debugging to see what error your CODE is generating.

Note: For undefined function wp_generate_attachment_metadata() error check Mark's answer.

Also, since you've scheduled the cron in plugin's activation hook, you must deactivate and then activate the plugin again if you change activation hook function. Using Crontrol Plugin, make sure there is not unnecessary cron registered in the backend.

Finally, check if in wp-config.php you have define( 'DISABLE_WP_CRON', true );. You must remove it (if it is there) or set it to false, if you want WP cron to run on normal WP load. Otherwise, you'll need to set cron with OS crontab (like shown at the beginning of my answer.)

7
  • can i not just run it with WP's buildin cronjob?
    – Mac
    Commented Mar 24, 2017 at 7:04
  • 1
    @Jùrgen, run what? your question lack details on what is it actually that you are doing and from the way it is written it reads like you are using the OS cron Commented Mar 24, 2017 at 7:06
  • @Mark Kaplun actually I'm saying multiple places (even in the title, that we are talking about a wp-cronjob). But i have no editted my question, so it says WP-conjob everywhere :)
    – Mac
    Commented Mar 24, 2017 at 7:36
  • @Jùrgen than why do you try to load wordpress? this is not how wordpress cron works. If you try to use the wordpress cron, you are doing it totally wrong Commented Mar 24, 2017 at 7:38
  • @Mark Kaplun what do you mean try to load wordpress? i have setup a WP-cronjob to do some download some pictures (if any new) and add them to the related posts. I'm not trying to load anything, but i expect a simple wordpress function works, when I'm running a WP-cronjob
    – Mac
    Commented Mar 24, 2017 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.