Delete posts in frontend
DOMJSPHP
<ul class="[email protected] [email protected]" uk-grid> <?php $args_post = array( 'posts_per_page' => -1, 'post_type' => 'post', 'post_status' => 'any', 'author' => wp_get_current_user()->ID ); $query_post = new WP_Query( $args_post ); if( $query_post->have_posts() ): while( $query_post->have_posts() ): $query_post->the_post();?> <li class="uk-position-relative link-cover"> <div class="uk-width-1-1 uk-background-default height-400 uk-position-relative uk-background-cover" data-src="<?php echo get_field('cover_src'); ?>" uk-img style="border-radius: 10px; box-shadow: 3px 3px 10px 0px rgba(0,0,0,0.5); overflow: hidden"> <div class="cover uk-position-top-left" style="width:100%;height:100%;background-color:rgba(0,0,0,0.5)"> <ul class="uk-flex uk-position-center uk-position-small uk-flex-around" style="width:80%"> <li><a class="uk-button uk-button-primary text-white text-xsmall uk-border-rounded" href="<?php echo home_url(); ?>/editor?post=<?php echo get_the_ID(); ?>" style="padding: 0 15px;">編輯</a></li> <li><a class="uk-button uk-button-primary text-white text-xsmall uk-border-rounded" href="<?php the_permalink(); ?>" target="_blank" rel="noopener norefererr" style="padding: 0 15px;">預覽</a></li> <li><a class="uk-button uk-button-danger text-white text-xsmall uk-border-rounded btnDelete" href="#" data-id="<?php echo get_the_ID(); ?>" style="padding: 0 15px;">刪除</a></li> <?php wp_nonce_field( 'ajax-delete-nonce', 'security' ); ?> </ul> </div> </div> <h3 class="uk-text-center uk-margin text-default-height"><?php the_title(); ?></h3> </li> </ul>
<script> var $ = jQuery.noConflict(); $(function(){ $('.btnDelete').on('click', function(){ var r = confirm('確定要刪除?'); if(r){ action = 'deletepost'; postid = $(this).attr('data-id'); security = $('#security').val(); $.ajax({ url: delete_params.ajaxurl, type: 'POST', dataType: 'json', data: { 'action': action, 'postId': postid, 'security': security }, success: function (data) { alert(data.msg); window.location.reload(); } }); } }) }) </script>
<?php function delete_scripts() { global $wp_query; wp_register_script( 'delete_post', '', '',null ); wp_localize_script( 'delete_post', 'delete_params', array( 'ajaxurl' => site_url(). '/wp-admin/admin-ajax.php' )); wp_enqueue_script( 'delete_post' ); } add_action( 'wp_enqueue_scripts', 'delete_scripts' ); function delete_ajax_handler(){ $nonce = $_POST['security']; if (!wp_verify_nonce($nonce, 'ajax-delete-nonce')) { wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求')); } $post_id = $_POST['postId']; wp_delete_post($post_id, true); echo json_encode( array( 'msg'=>"刪除成功!", ) ); die; } add_action('wp_ajax_deletepost', 'delete_ajax_handler');