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);
.
本文标签:
版权声明:本文标题:Action to create custom field based on shipping class works when manually triggered, but not on cron schedule 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736306079a1932824.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论