phpwordpresswoocommercecron

Cron to fire function in WordPress Plugin - wc_rest_set_uploaded_image_as_attachment not loading images


Currently the function will complete with out problems via a button on the admin side / plugin folder.

Products information updates as expected but the image fails only via Cron, Throwing internal error:

$image_url = wc_rest_upload_image_from_url( $pic_url_r,$pro_id);
$image_id1 = wc_rest_set_uploaded_image_as_attachment($image_url, $pro_id);

The Error

Uncaught Error: Cannot use object of type WP_Error as array in /home/public_html/wp-content/plugins/woocommerce/includes/wc-rest-functions.php:135

thrown in /home/public_html/wp-content/plugins/woocommerce/includes/wc-rest-functions.php on line 135

The error lands at function:

function wc_rest_set_uploaded_image_as_attachment? (dont have permission via cron)


The cron only works if i am logged in browser, How am I able to include those wp-admin functions for cron to have access?.

**Dumped ERROR: **


Array ( [woocommerce_rest_invalid_image] => Array ( [0] => Invalid image: Sorry, you are not allowed to upload this file type.


Solution

  • Permissions was the reason admin functions are not working as expected. Cron was not logged in technically. Work around was to emulate user with permissions during Cron. Setup a user in WP admin section with the right access.

    steps : create cron.php file

    Command Cron : */30 * * * curl https://example.com/cron.

    We want to access Cron.php as a webpage with the same environment as such, not direct.

        //cron will need to include
    
        wp-config.php 
        wp-load.php
    
        //https://gist.github.com/digisavvy/0cd5c8023105c17679811014b9decc7d
        login(){
           myfunction();
        }
    
      
    

    Automated wp login example script found here: https://gist.github.com/digisavvy/0cd5c8023105c17679811014b9decc7d

    Tailor the script in your cron.php as you need. log out after function complete.

    Result is to run admin functions from Cron in WordPress.