您可以在每次页面加载时触发的 init 挂钩上执行此操作。
首先,您必须获得所有产品。
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$products = new WP_Query( $args );
if ( $products->have_posts() ) { while ( $products->have_posts() ) { $products->the_post();
// your logic will go here.
} wp_reset_postdata(); }
现在计算天数。
$product = wc_get_product( get_the_ID() );
$datetime = $product->get_date_created();
$timezone = $datetime->getTimezone();
$now_time = new WC_DateTime();
$now_time->setTimezone($timezone);
$timestamp_diff = $now_time->getTimestamp() - $datetime->getTimestamp();
$data = timestamp_to_array( $timestamp_diff );
$days = $data['d'];
然后您可以使用wp_set_object_terms 和wp_remove_object_terms 来设置和删除类别。
// If the difference is less than 60, apply "NEW IN cat"
if ( $days < 60 ) {
wp_set_object_terms( get_the_ID(), 40, 'product_cat', true );
}else{
wp_remove_object_terms( get_the_ID(), 40, 'product_cat' );
}
完整代码。在您的活动主题functions.php文件中添加以下代码。
function add_category_to_product_for_certain_days(){
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$products = new WP_Query( $args );
if ( $products->have_posts() ) { while ( $products->have_posts() ) { $products->the_post();
$product = wc_get_product( get_the_ID() );
$datetime = $product->get_date_created();
$timezone = $datetime->getTimezone();
$now_time = new WC_DateTime();
$now_time->setTimezone($timezone);
$timestamp_diff = $now_time->getTimestamp() - $datetime->getTimestamp();
$data = timestamp_to_array( $timestamp_diff );
$days = $data['d'];
// If the difference is less than 60, apply "NEW IN cat"
if ( $days < 60 ) {
wp_set_object_terms( get_the_ID(), 40, 'product_cat', true );
}else{
wp_remove_object_terms( get_the_ID(), 40, 'product_cat' );
}
} wp_reset_postdata(); }
}
add_action( 'init', 'add_category_to_product_for_certain_days', 10, 1 );
function timestamp_to_array( $timestamp ) {
$d = floor($timestamp/86400);
$_d = ($d < 10 ? '0' : '').$d;
$h = floor(($timestamp-$d*86400)/3600);
$_h = ($h < 10 ? '0' : '').$h;
$m = floor(($timestamp-($d*86400+$h*3600))/60);
$_m = ($m < 10 ? '0' : '').$m;
$s = $timestamp-($d*86400+$h*3600+$m*60);
$_s = ($s < 10 ? '0' : '').$s;
return array('d' => $_d, 'h' => $_h, 'm' => $_m, 's' => $_s);
}
经过测试并且有效。