Skip to content

Instantly share code, notes, and snippets.

@dantetesta
Last active September 8, 2022 16:01
Show Gist options
  • Save dantetesta/0b08fe6127db7b1ade7b72c51363385d to your computer and use it in GitHub Desktop.
Save dantetesta/0b08fe6127db7b1ade7b72c51363385d to your computer and use it in GitHub Desktop.
/*
Cria um shortcode [remove_posts_user cpt_name="" label=""] para rermover todos os registros de um CPT.
EXEMPLO DE USO: Remover todos os registros do CPT Empresas
[remove_posts_user cpt_name="empresas" label="Remover Todas as Empresas"]
Basta por o trecho abaixo no functions.php do seu tema
*/
function remove_posts_user_shortcode_by_dante_testa( $atts ) {
$a = shortcode_atts( array(
'cpt_name' => '',
'label' => '',
), $atts );
$cpt_name = $a['cpt_name'];
$btn_label = $a['label'];
$output = '<button id="remove_posts">'.$btn_label.' &nbsp;<i class="fa fa-trash"></i></button>';
$output .= '<script>
jQuery(document).ready(function($) {
$("#remove_posts").click(function() {
if(confirm("Tem certeza que deseja remover todos os dados de ['.$cpt_name.'] ?")){
$.ajax({
url: "'.admin_url('admin-ajax.php').'",
type: "POST",
data: {
action: "remove_posts_user",
cpt_name: "'.$cpt_name.'",
author_id: "'.get_current_user_id().'",
},
success: function(response) {
window.location.href = window.location.href;
alert(response);
}
});
}
else{
return false;
}
});
});
</script>';
return $output;
}
add_shortcode( 'remove_posts_user', 'remove_posts_user_shortcode_by_dante_testa' );
function remove_posts_user_callback_byddt() {
$cpt_name = $_POST['cpt_name'];
$author_id = $_POST['author_id'];
$args = array(
'post_type' => $cpt_name,
'author' => $author_id,
'posts_per_page' => -1,
);
$posts = get_posts($args);
foreach ($posts as $post) {
wp_delete_post($post->ID, true);
}
echo 'Todos os dados sobre ['.$cpt_name.'] formam removidos';
wp_die();
}
add_action( 'wp_ajax_remove_posts_user', 'remove_posts_user_callback_byddt' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment