我正在为 Woocommerce 开发一个功能,该功能将添加一个切换按钮,用于快速将产品从“有货”更改为“缺货”,反之亦然,而无需更改“快速编辑”中的状态。我已经可以使用切换功能,但我还希望“库存”列能够在不刷新页面的情况下更新状态。这是我正在使用的 JS 文件:
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>');
}
}
});
事实证明我的脚本可以正常工作,无需任何额外的更改。我只需清除浏览器缓存即可!