I am working on a function for Woocommerce that will add a toggle button for quickly changing products from In Stock to Out of Stock or vice versa without having to change the status in Quick Edit. I’ve gotten the toggle to work, but I would also like the Stock column to update the status without refreshing the page. Here’s the JS file I’m using:
jQuery(document).ready(function($) {
$(document).on('click', '.toggle-stock', function(e) {
e.preventDefault();
var product_id = $(this).data('id');
var stock_status = $(this).data('status');
var button = $(this);
$.ajax({
url: customAdmin.ajax_url,
method: 'POST',
data: {
action: 'toggle_stock_status',
product_id: product_id,
stock_status: stock_status,
security: customAdmin.security
},
success: function(response) {
if (response.success) {
if (stock_status === 'instock') {
button.text('Make Out of Stock');
button.data('status', 'outofstock');
updateStockColumn(product_id, 'In stock', 'instock');
} else {
button.text('Make In Stock');
button.data('status', 'instock');
updateStockColumn(product_id, 'Out of stock', 'outofstock');
}
} else {
alert('Error toggling stock status');
}
}
});
function updateStockColumn(productId, stockStatus, stockClass) {
var row = $('#post-' + productId);
var stockColumn = row.find('td.is_in_stock.column-is_in_stock');
if (stockColumn.length) {
stockColumn.html('<mark class="' + stockClass + '">' + stockStatus + '</mark>');
}
}
});