Skip to content

Instantly share code, notes, and snippets.

@fariasf
Created October 18, 2017 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fariasf/95494d8aa7efc82367a9796b3d6cd177 to your computer and use it in GitHub Desktop.
Save fariasf/95494d8aa7efc82367a9796b3d6cd177 to your computer and use it in GitHub Desktop.
Low stock notification per product (adding custom fields)
<?php
/**
* Custom product field to set low stock threshold
* Requires WooCommerce 3.0
*/
function sp_custom_product_stock_threshold_field() {
global $post;
woocommerce_wp_text_input( array(
'id' => '_low_stock_threshold',
'label' => __( 'Low stock threshold', 'textdomain' ),
'desc_tip' => true,
'description' => __( 'Set the low stock threshold for this product', 'textdomain' ),
'type' => 'number',
'default' => get_option( 'woocommerce_notify_low_stock_amount' ), // Default to global
'custom_attributes' => array(
'step' => 'any'
),
'data_type' => 'stock'
) );
}
add_action( 'woocommerce_product_options_stock_fields', 'sp_custom_product_stock_threshold_field' );
/**
* Save the custom fields.
*/
function sp_save_custom_product_inventory_settings( $post_id ) {
if ( isset( $_POST['_low_stock_threshold'] ) ) :
update_post_meta( $post_id, '_low_stock_threshold', absint( $_POST['_low_stock_threshold'] ) );
endif;
}
add_action( 'woocommerce_process_product_meta', 'sp_save_custom_product_inventory_settings' );
/**
* Send custom low stock notifications per product
* Requires WooCommerce 3.0
*
* @param WC_Order $order
*/
function sp_custom_low_stock_notification_improved_product_30( $order ) {
foreach ( $order->get_items() as $item ) {
if ( $item->is_type( 'line_item' ) && ( $product = $item->get_product() ) && $product->managing_stock() ) {
$new_stock = $item->get_quantity();
$low_stock_threshold = get_post_meta( $product->get_id(), '_low_stock_threshold', true );
if ( ! empty( $low_stock_threshold ) && $new_stock < $low_stock_threshold ) {
do_action( 'woocommerce_low_stock', $product );
}
}
}
}
add_action( 'woocommerce_reduce_order_stock', 'sp_custom_low_stock_notification_improved_product_30', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment