Hey, I spend a good time to write a code for your requirement.
Step 1: Add JavaScript
Add the following JavaScript to your admin area. You can enqueue it using admin_enqueue_scripts
.
jQuery(document).ready(function($) {
$('#target').on('click', function() {
if (confirm("Do you really want to delete prices?")) {
$.ajax({
url: ajaxurl, // WordPress AJAX URL
type: 'POST',
data: {
action: 'reset_price_fields', // Custom action to be processed in PHP
author_id: $(this).data('author-id') // Pass the author ID
},
success: function(response) {
alert(response.message); // Show success message
},
error: function() {
alert('Error resetting prices.'); // Show error message
}
});
}
});
});
Step 2: Add PHP Function
Add this function to your theme’s functions.php
file or a custom plugin.
add_action('wp_ajax_reset_price_fields', 'reset_price_fields');
function reset_price_fields() {
// Check for the required parameter
if (!isset($_POST['author_id'])) {
wp_send_json_error(['message' => 'No author ID provided.']);
exit;
}
$author_id = intval($_POST['author_id']);
$args = [
'post_type' => 'apartment', // Change this to your custom post type
'author' => $author_id,
'posts_per_page' => -1 // Get all posts
];
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
// Get current custom fields
$custom_fields = get_post_meta($post_id);
// Prepare an array of custom fields to reset
$fields_to_reset = ['price_field_1', 'price_field_2']; // Replace with your custom field keys
foreach ($fields_to_reset as $field) {
if (array_key_exists($field, $custom_fields)) {
// Delete the specific custom field
delete_post_meta($post_id, $field);
}
}
}
wp_send_json_success(['message' => 'Prices have been reset successfully.']);
} else {
wp_send_json_error(['message' => 'No posts found for this author.']);
}
wp_reset_postdata();
exit;
}
Step 3: HTML
Make sure to include the data-author-id
attribute in your button to pass the author’s ID.
<button type="button" id="target" data-author-id="<?php echo get_current_user_id(); ?>">Cancella prezzi</button>
Let me know if this works for you & if requires any further modification.