将以下代码添加到自定义插件
将类别添加到新产品
function set_new_product_cat( $post_id, $post, $update ) {
if("product" === $post->post_type){
// Exit out as we are updating an existing product
if ( $update ) {
return;
}
//Appends the category 35 to the product
wp_set_post_categories( $post->ID, 35, true);
}
}
add_action( \'wp_insert_post\', \'set_new_product_cat\', 10, 3 );
这是为了设置一个cron任务,每天检查一次30天以前仍设置并取消设置类别的产品
function remove_new_product_cat_deactivate() {
wp_clear_scheduled_hook( \'remove_new_product_cat_cron\' );
}
add_action(\'init\', function() {
add_action( \'remove_new_product_cat_cron\', \'remove_new_product_cat_run_cron\' );
register_deactivation_hook( __FILE__, \'remove_new_product_cat_deactivate\' );
if (! wp_next_scheduled ( \'remove_new_product_cat_cron\' )) {
wp_schedule_event( time(), \'daily\', \'remove_new_product_cat_cron\' );
}
});
function remove_new_product_cat_run_cron() {
// Get all products older then 30 days that have the category with id 35
$args = array(
\'numberposts\' => -1,
\'category\' => 35,
\'post_type\' => \'product\',
\'date_query\' => array(
\'before\' => date(\'Y-m-d\', strtotime(\'-30 days\'))
)
);
$products = get_posts($args);
// Loop trough the products
foreach ( $products as $product) {
// Grab an array of currently set categories
$cats = wp_get_post_categories($product);
// Remove 35 from the list
if (($key = array_search(35, $cats)) !== false) {
unset($messages[$key]);
}
// Update the categories overwriting existing ones
wp_set_post_categories( $post->ID, $cats, false);
}
}