Wordpress - Bulk change products status
/** | |
* Aggiungo una notice nella pagina dei prodotti con due bottoni: | |
* uno per nascondere (mettere in bozza), l'altro per pubblicare tutti i prodotti. | |
*/ | |
add_action( "admin_notices", function() { | |
// Verifico che sia la pagina corretta | |
$screen = get_current_screen(); | |
if ( 'edit-product' != $screen->id ) return; | |
$_wpnonce = wp_create_nonce('la_mia_stringa_di_sicurezza'); | |
$url_draft = add_query_arg( array( 'change_all_products_status' => 'draft', '_wpnonce' => $_wpnonce ), $_SERVER["REQUEST_URI"] ); | |
$url_publish = add_query_arg( array( 'change_all_products_status' => 'publish', '_wpnonce' => $_wpnonce ), $_SERVER["REQUEST_URI"] ); | |
?> | |
<div class='updated'> | |
<p> | |
Modifica lo stato di 250 prodotti per volta. | |
<a class='button button-primary' style='margin:0.25em 1em' href='<?php echo $url_draft ?>'>Metti in bozza</a> | |
<a class='button button-primary' style='margin:0.25em 1em' href='<?php echo $url_publish ?>'>Pubblica</a> | |
</p> | |
</div> | |
<?php | |
}); | |
add_action( "admin_init", function() { | |
// Esegui solo se nella URL è presente "change_all_products_status" e la verifica del nonce va a buon fine. | |
if ( !isset($_GET["change_all_products_status"]) | |
|| !isset($_GET["_wpnonce"]) || !wp_verify_nonce($_GET["_wpnonce"], 'la_mia_stringa_di_sicurezza') | |
) { | |
return; | |
} | |
$query = new WP_Query(array( | |
'post_type' => 'product', | |
'post_status' => $_GET["change_all_products_status"] == 'publish' ? 'draft' : 'publish', | |
'posts_per_page' => 250, | |
)); | |
while ($query->have_posts()) : $query->the_post(); | |
$post = array( | |
'ID' => get_the_ID(), | |
'post_status' => $_GET['change_all_products_status'] | |
); | |
wp_update_post($post); | |
endwhile; | |
wp_reset_query(); | |
// Rimuovo dalla URL il parametro in modo che si eviti di ricaricare la pagina e rieseguire il codice. | |
wp_safe_redirect( remove_query_arg( array( 'change_all_products_status' ), wp_get_referer() ) ); | |
die(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment