根据自定义输入字段更新 WooCommerce 管理产品列表中的库存数量,这是我之前对我的一个问题的回答。
以下代码为数量列添加一个自定义按钮,按下按钮时会更新数量并刷新当前数量。尝试在按下按钮后添加加载微调器,但无法加载。
这是 functions.php 文件中的代码:
// Add input fields to stock status column// change default stock
add_filter('woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );
function filter_woocommerce_admin_stock_html($stock_html, $product) {
if ( $product->managing_stock() ) {
return '';
}
return $stock_html;
}
// Add input fields to stock status column
add_action( 'manage_product_posts_custom_column', 'product_stock_quantity_column_content', 10, 2 );
function product_stock_quantity_column_content( $column, $product_id ) {
if ( $column === 'is_in_stock' ) {
global $product;
if ( $product->managing_stock() ) {
$stock_html = sprintf('
',
$product_id, $product->get_stock_quantity('edit'), $product_id, $product_id, $product_id);
if ( $product->is_on_backorder() ) {
$stock_html .= '' . __( 'On backorder', 'woocommerce' ) . '';
} elseif ( $product->is_in_stock() ) {
$stock_html .= '' . __( 'In stock', 'woocommerce' ) . '';
} else {
$stock_html .= '' . __( 'Out of stock', 'woocommerce' ) . '';
}
echo $stock_html .' (' . wc_stock_amount( $product->get_stock_quantity() ) . ')';
}
}
}
// WP Admin Ajax receiver
add_action('wp_ajax_update_stock_quantity', 'update_stock_quantity_ajax');
function update_stock_quantity_ajax() {
if (isset($_POST['product_id']) && isset($_POST['update_qty'])) {
$product = wc_get_product(intval($_POST['product_id']));
$product->set_stock_quantity(intval($_POST['update_qty']));
$id = $product->save();
if ( $product->is_on_backorder() ) {
$stock_html = '' . __( 'On backorder', 'woocommerce' ) . '';
} elseif ( $product->is_in_stock() ) {
$stock_html = '' . __( 'In stock', 'woocommerce' ) . '';
} else {
$stock_html = '' . __( 'Out of stock', 'woocommerce' ) . '';
}
$stock_html .= ' (' . wc_stock_amount( $product->get_stock_quantity() ) . ')';
echo $stock_html;
}
wp_die(); // Exit silently (Always at the end to avoid an Error 500)
}
// jQuery Ajax
add_action('admin_footer', 'update_stock_quantity_js');
function update_stock_quantity_js() {
global $pagenow, $typenow;
if( 'edit.php' === $pagenow && 'product' === $typenow ) :
?>
还导入了font Awesome库,现在按下按钮后,按钮就会消失,出现一个空框。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号