Skip to content

Instantly share code, notes, and snippets.

@taciara
Created August 16, 2023 17:11
Show Gist options
  • Save taciara/6b7f062ac64b7b30f37d37a979564d74 to your computer and use it in GitHub Desktop.
Save taciara/6b7f062ac64b7b30f37d37a979564d74 to your computer and use it in GitHub Desktop.
Adicionar ou remover automaticamente produtos da categoria "promoções" com base no preço promocional
<?php
// Adicionar ou remover automaticamente produtos da categoria "promoções" com base no preço promocional
function update_promotion_category_based_on_sale() {
$promo_category = get_term_by('slug', 'promocoes', 'product_cat'); // Substitua 'promocoes' pela slug da categoria "promoções"
if (!$promo_category) {
return;
}
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_sale_price',
'value' => '',
'compare' => '!='
),
array(
'key' => '_regular_price',
'value' => '',
'compare' => '!='
)
)
);
$products = new WP_Query($args);
if ($products->have_posts()) {
while ($products->have_posts()) {
$products->the_post();
$product_id = get_the_ID();
$terms = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
if (get_post_meta($product_id, '_sale_price', true) && get_post_meta($product_id, '_regular_price', true)) {
if (!in_array($promo_category->term_id, $terms)) {
$terms[] = $promo_category->term_id;
wp_set_post_terms($product_id, $terms, 'product_cat');
}
} else {
if (in_array($promo_category->term_id, $terms)) {
$terms = array_diff($terms, array($promo_category->term_id));
wp_set_post_terms($product_id, $terms, 'product_cat');
}
}
}
}
wp_reset_postdata();
}
add_action('wp_loaded', 'update_promotion_category_based_on_sale');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment