I’m writing this question because I have an AJAX request for deleting posts into my website that is working fine but I have duplicated it multiple times to match the URL for different Custom Post Type that I have in the page.
Here the original code:
jQuery(".delete-listing-btn").on("click", function(e) {
var thisPost = jQuery(e.target).parents(".agent-dashboard-listing-card")
jQuery.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', msSiteData.nonce);
},
url: 'https://mallorca-select.com/wp-json/wp/v2/properties-for-sale/' + thisPost.data('id'),
type: 'DELETE',
success: function () {
alert(" Listing Deleted Successfully! ");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
});
In these functions the only thing that changes is a part of the URL request like this:
‘https://example.com/wp-json/wp/v2/post-type-1/’ + thisPost.data(‘id’)
‘https://example.com/wp-json/wp/v2/post-type-2/’ + thisPost.data(‘id’)
‘https://example.com/wp-json/wp/v2/post-type-3/’ + thisPost.data(‘id’)
‘https://example.com/wp-json/wp/v2/post-type-4/’ + thisPost.data(‘id’)
I’m wondering if there is a method for detecting the post type of the post where the delete button is clicked and inject inside the URL request so I don’t have to duplicate it 4 times only to change the custom post type inside the url.
2
Answers
Move the common AJAX code to a separate function and pass the specific URL you need in each case.
To do what you require you can use another
data
attribute to hold the post type URL route – as you already are for theid
: