admin管理员组

文章数量:1122832

I am trying to schedule an action to run every minute to get the shipping class of all products and store it into a new custom field called product_shipping_class. The snippet below I saved using WPCode:

<?php
// WordPress Admin create custom fields


// Unschedule all events attached to a given hook
// wp_clear_scheduled_hook( $hook='custom_field_product_shipping_class', $args=array(), $wp_error=false );


// Add custom cron schedules
add_filter( $hook_name='cron_schedules', $callback='custom_cron_schedules', $priority=10, $accepted_args=1 );

function custom_cron_schedules( $schedules ) {
    if( !isset( $schedules['every_minute'] ) ) {
        $schedules['every_minute'] = array( 'interval' => 60, 'display' => __('Once every minute') );
    }

    return $schedules;
}


// Schedule cron jobs (UTC time)
add_action( $hook_name='init', $callback='schedule_custom_cron_job', $priority=10, $accepted_args=1 );

function schedule_custom_cron_job() {
    if ( ! wp_next_scheduled( $hook='custom_field_product_shipping_class', $args=array() ) ) {
        wp_schedule_event( $timestamp=time(), $recurrence='every_minute', $hook= 'custom_field_product_shipping_class', $args=array(), $wp_error=false );
    }
}


// Custom Field 'product_shipping_class'
add_action( $hook_name='custom_field_product_shipping_class', $callback='add_custom_field_product_shipping_class', $priority=10, $accepted_args=1 );

function add_custom_field_product_shipping_class() {
    if ( WC() ) {
        // Get all products
        $products = wc_get_products( array('limit' => -1) );

        foreach ( $products as $product ) {
            update_post_meta( $post_id=$product->get_id(), $meta_key='product_shipping_class', $meta_value=$product->get_shipping_class(), $prev_value='' );
        }
    }
}

I am sure that the custom_field_product_shipping_class action works, because when I run on WP Console the command do_action( 'custom_field_product_shipping_class'); it generated the new product_shipping_class custom field.

I am also sure that the cron job is scheduled, because when I run on WP Console the command echo date( 'Y-m-d H:i:s', wp_next_scheduled( $hook='custom_field_product_shipping_class', $args=array() ) ); I get the time where it is was scheduled.

I have also checked my wp-config.php file and the cron job setting is set to define('DISABLE_WP_CRON', false);.

本文标签: