У меня есть пользовательский плагин, над которым я работаю, чтобы эффективно уменьшить общее количество акций на количество c, которое вводится в настраиваемое поле. Я, кажется, там около 90% - похоже, хорошо работает на моем сайте тестирования localhost. Но когда я перемещаю его вживую, мы начинаем видеть ошибки, когда заказы не go заканчиваются на концах пользователей, и они получают красную пустую полосу ошибок над оформлением без сообщения.
Основная цель заключается в том, чтобы по существу запускать этот сценарий только для продуктов, для которых установлен пользовательский флажок.
Я не являюсь опытным разработчиком, поэтому я обращаюсь к специалистам, чтобы выяснить, не может ли кто-нибудь выбрать мой плагин и сообщить, что я делаю неправильно, что можно сделать лучше и др. c. Спасибо всем, кто может помочь заранее.
<?php
// ---------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------- //
// ---------------------------- INVENTORY CONTROL BY WEIGHT ----------------------------- //
// ---------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------- //
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// ---------------------------------------------------------------------------------------- //
// -------------------------- ALLOW DECIMALS IN STOCK QUANTITY --- ----------------------- //
// ---------------------------------------------------------------------------------------- //
add_action( 'plugins_loaded', 'allow_decimals' );
function allow_decimals() {
// Removes the WooCommerce filter, that is validating the quantity to be an int
remove_filter('woocommerce_stock_amount', 'intval');
// Add a filter, that validates the quantity to be a float
add_filter('woocommerce_stock_amount', 'floatval');
}
// ---------------------------------------------------------------------------------------- //
// -------------------------- REDUCE WEIGHT BASED ON CUSTOM FIELD ----------------------- //
// ---------------------------------------------------------------------------------------- //
add_filter( 'woocommerce_order_item_quantity', 'filter_order_item_quantity', 10, 4 );
function filter_order_item_quantity( $quantity, $order, $item )
{
$product = $item->get_product();
$term_name = $product->get_meta( 'custom_field', true );
$product = wc_get_product( $item->get_product()->get_parent_id() );
$stock_weight_checkbox = $product->get_meta( '_stock_weight_checkbox', true );
// 'pa_weight' attribute value is "15 grams" - keep only the numbers
$quantity_grams = preg_replace('/[^0-9.]+/', '', $term_name);
// new quantity
if( 'yes' == $stock_weight_checkbox && is_numeric ( $quantity_grams ) && $quantity_grams != 0 )
$quantity *= $quantity_grams;
return $quantity;
}
add_action('woocommerce_before_main_content', 'quantity_control', 10, 1);
function quantity_control( $post_id ) {
$stock_weight_checkbox = get_post_meta( get_the_id(),'_stock_weight_checkbox', true );
if ( 'yes' == $stock_weight_checkbox ) {
// ------------------------- ENSURE VARIATION PRICE DISPLAYS ---------------------------- //
add_filter( 'woocommerce_show_variation_price', '__return_true' );
// ---------------------------------------------------------------------------------------- //
// ------------------------- VALIDATE WEIGHT & INVENTORY AMOUNT ------------------------- //
// ---------------------------------------------------------------------------------------- //
function validate_attribute_weight( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Get custom field
$weight = get_post_meta( $variation_id, 'custom_field', true );
$product = wc_get_product( $product_id );
$stock_weight_checkbox = $product->get_meta( '_stock_weight_checkbox', true );
if ( ! empty( $weight ) ) {
// Get current product stock
$product_stock = $product->get_stock_quantity();
// ( Weight * quantity ) > product stock
if( ( ( $weight * $quantity ) > $product_stock ) ) {
wc_add_notice( sprintf( 'Sorry, you cannot add <strong>' . $quantity . '</strong> bags with <strong>' . $weight .'</strong> of <strong>%1$s</strong> to the cart because there are only <strong>%2$s grams</strong> left in our inventory. Please choose a lesser amount. We hope to have more in stock shortly.', $product->get_name(), $product_stock ), 'error' );
$passed = false;
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'validate_attribute_weight', 10, 5 );
// ---------------------------------------------------------------------------------------- //
// ---------------------------- HIDE OUT OF STOCK VARIATIONS ----------------------------- //
// ---------------------------------------------------------------------------------------- //
/**
* variation_is_visible
*
* @param bool $bool
* @param int $product_id
* @param obj $variation
* @return bool
*/
add_filter( 'woocommerce_variation_is_visible', 'iconic_variation_is_visible', 10, 4 );
function iconic_variation_is_visible( $bool, $variation_id, $product_id, $variation ) {
$weight = get_post_meta( $variation_id, 'custom_field', true );
// Get product object
$product = wc_get_product( $product_id );
// Get current product stock
$product_stock = $product->get_stock_quantity();
if ( ! empty( $weight && $weight <= $product_stock ) ) {
return true;
return $bool;
}
}
// ---------------------------------------------------------------------------------------- //
// ---------------------------- ENFORCE MAX STOCK QUANTITY ------------------------------ //
// ---------------------------------------------------------------------------------------- //
add_filter( 'woocommerce_available_variation', 'customizing_available_variation', 10, 5 );
function customizing_available_variation( $args, $product, $variation ) {
$initial_weight = get_post_meta( $variation->get_id(), 'custom_field', true );
$product_stock = $variation->get_stock_quantity();
// 'pa_weight' attribute value is "15 grams" - keep only the numbers
$weight = preg_replace('/[^0-9.]+/', '', $initial_weight);
$quantity = floor($product_stock/$weight);
if( is_woocommerce() ){
$args['max_qty'] = $quantity;
}
return $args;
}
// ---------------------------------------------------------------------------------------- //
// ---------------------------- END GRAM INVENTORY PLUGIN -------------------------------- //
// ---------------------------------------------------------------------------------------- //
function show_stock() {
global $product;
if ( $product->get_stock_quantity() ) { // if manage stock is enabled
if ( number_format($product->get_stock_quantity(),0,'','') < 14 ) { // if stock is low
echo '<div class="remaining" style="font-weight: 600; color: #4c4c4c;">Only <strong>' . number_format($product->get_stock_quantity(),0,'','') . ' grams</strong> left in stock.</div>';
}
}
}
add_action('woocommerce_single_variation','show_stock', 10);
function my_wc_hide_in_stock_message( $html, $text, $product ) {
$availability = $product->get_availability();
if ( isset( $availability['class'] ) && 'in-stock' === $availability['class'] ) {
return '';
}
return $html;
}
add_filter( 'woocommerce_stock_html', 'my_wc_hide_in_stock_message', 10, 3 );
}}
// ---------------------------------------------------------------------------------------- //
// ------------------------ CONFIRM IF PRODUCT SHOULD REDUCE BY GRAM -------------------- //
// ---------------------------------------------------------------------------------------- //
// The code for displaying WooCommerce Product Custom Fields
add_action( 'woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields', 5 );
// Following code Saves WooCommerce Product Custom Fields
add_action( 'woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save' );
/**
* Create new fields for variations
*
*/
function woocommerce_product_custom_fields() {
global $woocommerce, $post;
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_stock_weight_checkbox',
'label' => __('Weigh by gram?', 'woocommerce' ),
'description' => __( 'Yes, reduce stock by \'Amount in Bag\' count.', 'woocommerce' ),
)
);
}
/**
* Save new fields for variations
*
*/
function woocommerce_product_custom_fields_save($post_id)
{
//WooCommerce Custom Checkbox
$woocommerce_custom_product_checkbox = isset($_POST['_stock_weight_checkbox']) ? 'yes' : 'no';
update_post_meta($post_id, '_stock_weight_checkbox', $woocommerce_custom_product_checkbox);
}
add_action('woocommerce_before_single_product', 'shoot_the_variable');
function shoot_the_variable() {
$stock_weight_checkbox = get_post_meta( get_the_id(),'_stock_weight_checkbox', true );
}