在 WordPress 中,所有内容都被视为不同的帖子
post_type,所以每当更新帖子/产品时save_post 是
调用。
function wh_trashOutOfStockProduct($post_id, $post, $update) {
$post_type = get_post_type($post_id);
// If this isn't a 'product' post, don't update it.
if ('product' != $post_type)
return;
$product = wc_get_product($post_id);
//if product is Out of Stock trash it
if (!$product->is_in_stock()) {
wp_trash_post($post_id);
}
}
add_action('save_post', 'wh_trashOutOfStockProduct', 10, 3);
代码进入您的活动子主题(或主题)的function.php 文件。或者也可以在任何插件 php 文件中。
更新一次性使用功能
add_action('wp', 'wh_trashAllProductOnce');
function wh_trashAllProductOnce()
{
$params = [
'posts_per_page' => -1,
'post_type' => 'product'
];
$wc_query = new WP_Query($params);
if ($wc_query->have_posts()) :
while ($wc_query->have_posts()) :
$wc_query->the_post();
$product_id = get_the_ID();
$product = wc_get_product($product_id);
//if product is Out of Stock trash it
if (!$product->is_in_stock())
{
wp_trash_post($product_id);
}
endwhile;
wp_reset_postdata();
else:
_e('No Products');
endif;
}
在活动主题functions.php 文件中添加以上代码并运行您的网站只运行一次然后删除以上代码,它将丢弃所有缺货产品。
更新
如果您希望将代码保留更长时间,请减少查询和执行时间。
add_action('admin_init', 'wh_trashAllProductOnce');
function wh_trashAllProductOnce() {
$current_user = wp_get_current_user();
//if loggedin user does not have admin previlage
if (!user_can($current_user, 'administrator')) {
return;
}
$params = [
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish'
];
$wc_query = new WP_Query($params);
if ($wc_query->have_posts()) :
while ($wc_query->have_posts()) :
$wc_query->the_post();
$product_id = get_the_ID();
$product = wc_get_product($product_id);
//if product is Out of Stock trash it
if (!$product->is_in_stock()) {
wp_trash_post($product_id);
}
endwhile;
wp_reset_postdata();
endif;
}
将上述代码添加到活动主题functions.php 文件中,每当管理员登录仪表板并访问任何后端页面时,都会触发此功能。
请注意:建议使用以上任何一种方法
仅一次,或者在您需要时取消注释功能使用
然后再次评论它。
希望这会有所帮助!