$('.btn-export').on('click',function(){
$.ajax({
url:"<?php echo admin_url('admin-ajax.php') ?>",
type:"POST",
data:{
action:"export_news_cpt",
},
success:function(response)
{
if (response !== 0) {
Swal.fire({
icon: "success",
title: "Downloaded",
text: "Thankyou for downloading this file",
});
var link = document.createElement('a');
link.href = 'data:text/csv,' + encodeURIComponent(response);
link.download = 'file.csv';
link.click();
} else {
Swal.fire({
icon: "error",
title: response.data.message,
text: "Something went wrong!",
});
}
},
error : function (xhr , status,error)
{
alert("AJAX Response:"+error);
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
add_action('wp_ajax_nopriv_export_data', 'export_data');
add_action('wp_ajax_export_data', 'export_data');
function export_data()
{
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$args = [
'post_type' => 'book',
'posts_per_page' => -1
];
$query = new WP_Query($args);
if ($query->have_posts()) {
$csv = 'Post ID,Post Type,Post Title,Post DateTime,Book Author ,Publisher Name,Price,Genre,Post Thumbanil ';
while ($query->have_posts()) {
$query->the_post();
$post = $query->post;
$post_id = get_the_ID();
$post_type = get_post_type();
$post_title = get_the_title();
$post_date_time = get_the_date() . '' . get_the_time();
$post_book_author = get_post_meta($post_id, 'author_name', true);
$post_publisher_name = get_post_meta($post_id, 'publisher_name', true);
$post_book_price = get_post_meta($post_id, 'book_price', true);
$post_book_genre = get_post_meta($post_id, 'book_genre', true);
$post_thumbnail_url = get_the_post_thumbnail_url($post_id);
$csv .= '"' . $post_id . '","' . $post_type . '","' . $post_title . '","' . $post_date_time . '","' . $post_book_author . '","' . $post_publisher_name . '","' . $post_book_price . '","' . $post_book_genre . '","' . $post_thumbnail_url . '"' . '"\n';
}
wp_reset_postdata();
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
echo $csv;
exit;
} else {
echo 0;
}
} else {
wp_send_json_error(array("message" => "REQUEST METHOD POST"));
}
}