Мне нужно выяснить, как удалить продукт (ы) из определенной категории, когда заказ, связанный с ним, завершен (помечен как завершенный) в WooCommerce.
Ниже приведен порядок настройки продукта.пользователям разрешено создавать продукт из внешнего интерфейса, а при создании продукта / продуктов он назначается определенной категории.После покупки пользователем, заказу присваивается продукт (ы).
Теперь я хочу иметь возможность автоматически удалять продукт после завершения заказа, назначенного продукту (ам).
Я проверил этот вопрос ( Как я могу удалить определенный товар из выполненного заказа в woocommerce? ), но мне это не помогло, а также этот вопрос ( Добавить временный продукт Woocommerce )
Ниже приведен код HTML для формы интерфейса
<form id="co_form" method="post" action="#" class="" data-url="<?php echo admin_url('admin-ajax.php'); ?>">
<div class="form-group">
<label for="co_currency"><?php _e('Select Currency', 'izzycart-function-code'); ?></label>
<select class="form-control" id="co_currency" name="co_currency">
<option value="USD">USD</option>
<option value="RMB">RMB</option>
</select>
</div>
<div id="is_phone" class="form-group">
<label class="disInBlk" for="co_isPhone"><?php _e('Is this order a Phone item?','izzycart-function-code').':'; ?></label>
<input type="checkbox" name="co_isPhone" id="co-isPhone" <?php echo (isset($_POST['co_isPhone'])?'checked="checked"':'') ?>>
</div>
<div id="is_amazon" class="form-group">
<label class="disInBlk" for="co_isAmazon"><?php _e('Is this an Amazon Product?','izzycart-function-code').':'; ?></label>
<input type="checkbox" name="co_isAmazon" id="co-isAmazon" <?php echo (isset($_POST['co_isAmazon'])?'checked="checked"':'') ?>>
</div>
<div id="is_express" class="form-group no_express">
<label class="disInBlk" for="co_isExpress"><?php _e('Express Delivery?','izzycart-function-code').':'; ?></label>
<input type="checkbox" name="co_isExpress" id="co-isExpress" <?php echo (isset($_POST['co_isExpress'])?'checked="checked"':'') ?>>
</div>
<div class="form-group">
<label for="co_productTitle"><?php _e('Product Name/Title','izzycart-function-code').':'; ?></label>
<input type="text" name="co_productTitle" class="form-control" id="co-productTitle">
<div id="pt_error" class="co-error no"></div>
</div>
<div class="form-group">
<label for="co_productLink"><?php _e('Product URL','izzycart-function-code').':'; ?></label>
<input type="text" name="co_productLink" class="form-control" id="co-productLink" placeholder="<?php _e('http://...', 'izzycart-function-code'); ?>">
<div id="pl_error" class="co-error no"></div>
</div>
<div class="form-group">
<label for="co_productPriceUSD"><?php _e('Product Price (USD)','izzycart-function-code').':'; ?></label>
<input type="number" name="co_productPriceUSD" class="form-control" id="co-productPriceUSD" step="0.01">
<div id="pp_error" class="co-error no"></div>
</div>
<div class="form-group">
<label for="co_productShippingFee"><?php _e('Shipping Fee of Product/Item','izzycart-function-code').':'; ?></label>
<div class="co-desc"><?php echo __('N.B: If the product is FREE shipping from the store you\'re buying from, enter 0 as the shipping fee.', 'izzycart-function-code'); ?></div>
<input type="number" name="co_productShippingFee" class="form-control" id="co_productShippingFee" step="0.01">
<div id="ps_error" class="co-error no"></div>
</div>
<div class="form-group">
<label for="co_productPriceNGN"><?php _e('Product Price Converted to NGN','izzycart-function-code').':'; ?></label>
<input type="number" name="co_productPriceNGN" class="form-control" id="co-productPriceNGN" readonly>
</div>
<div id="co_dWeight" class="form-group">
<label for="co_productWeightKG"><?php _e('Weight (in KG)','izzycart-function-code').':'; ?></label>
<input type="number" name="co_productWeightKG" class="form-control" id="co-productWeightKG" step="0.001">
<div id="pw_error" class="co-error no"></div>
</div>
<div class="form-group-btn">
<input type="submit" name="co_submit" class="form-control" id="co-submit" value="<?php echo _e('Place Your Order', 'izzycart-function-code'); ?>">
<input type="hidden" name="amountNGNUpdated" value="<?php echo $ExhangeRateUSD; ?>" id="CurrencyEX">
<input type="hidden" id="currentCOUser" name="currentCOUser" value="<?php echo $usersID; ?>"> <!--$userID Gets the User ID. e.g 1 for administrator-->
</div>
<div class="response">
<div id="spinner" class="spin"><span id="is_loading" class="loading"></span></div>
<div id="co_success" class="co-success no"></div>
<div id="co_error" class="co-error-call no"></div>
</div>
</form>
, а ниже - код jQuery, который используется для проверки формы и отправки данных через Ajax
jQuery(document).ready( function($){
$('#co_form').on('submit', function(e) {
e.preventDefault();
$('.fielderr').removeClass('fielderr');
$('#pt_error, #co_error').addClass('no');
$('#pl_error, #co_error').addClass('no');
$('#pp_error, #co_error').addClass('no');
$('#ps_error, #co_error').addClass('no');
$('#pw_error, #co_error').addClass('no');
var coFormItself = $(this),
userProductTitle = coFormItself.find('#co-productTitle').val(),
userProductURL = coFormItself.find('#co-productLink').val(),
userProductPrice = coFormItself.find('#co-productPriceUSD').val(),
userShippingPrice = coFormItself.find('#co_productShippingFee').val(),
userProductWeightS = userProductWeight = coFormItself.find('#co-productWeightKG').val(),
productCategory = coFormItself.find('#productCategoryUpdate').val(),
userWhoSubmittedForm = coFormItself.find('#currentCOUser').val(),
is_PhoneProduct = coFormItself.find("#co-isPhone").prop("checked") ? 'Yes' : 'No',
is_AmazonProduct = coFormItself.find("#co-isAmazon").prop("checked") ? 'Yes' : 'No',
is_ExpressDelivery = coFormItself.find("#co-isExpress").prop("checked") ? 'Yes' : 'No',
productCurrency = coFormItself.find('#co_currency').val(),
ajaxurl = coFormItself.data('url');
//Validate Product Title
if(userProductTitle === '') {
$('#co-productTitle').addClass('fielderr');
if ( $('#pt_error, #co_error').hasClass('no') ) {
$('#pt_error, #co_error').removeClass('no');
$('#pt_error').text('This field is required');
$('#co_error').text('Product title field is incorrect');
}
return
}
//Validate Product URL
if(userProductURL === '') {
$('#co-productLink').addClass('fielderr');
if ( $('#pl_error, #co_error').hasClass('no') ) {
$('#pl_error, #co_error').removeClass('no');
$('#pl_error').text('This field is required');
$('#co_error').text('Product URL field is incorrect');
}
return
}
if ( userProductURL && !userProductURL.match(/^http([s]?):\/\/.*/) ) {
$('#co-productLink').addClass('fielderr');
if ( $('#pl_error, #co_error').hasClass('no') ) {
$('#pl_error, #co_error').removeClass('no');
$('#pl_error').text('Please enter a valid URL. URL must contain http:// or https://');
$('#co_error').text('Product URL field is incorrect');
}
return
}
if ( is_AmazonProduct == 'Yes' && (userProductURL.toLowerCase().indexOf("amazon.com") == -1) ) {
$('#co-productLink').addClass('fielderr');
if ( $('#pl_error, #co_error').hasClass('no') ) {
$('#pl_error, #co_error').removeClass('no');
$('#pl_error').text('This is not an Amazon product. Please enter a valid amazon product link.');
$('#co_error').text('Product URL field is incorrect');
}
return
}
//Validate Product Price
if(userProductPrice === '' || userProductPrice == 0 ) {
$('#co-productPriceUSD').addClass('fielderr');
if ( $('#pp_error, #co_error').hasClass('no') ) {
$('#pp_error, #co_error').removeClass('no');
$('#pp_error').text('This field is required');
$('#co_error').text('Product price field is incorrect');
}
return
}else if ( userProductPrice < 0 ) {
$('#co-productPriceUSD').addClass('fielderr');
if ( $('#pp_error, #co_error').hasClass('no') ) {
$('#pp_error, #co_error').removeClass('no');
$('#pp_error').text('Product Price cannot be a negative value. Kindly enter a valid product price');
$('#co_error').text('Product price field is incorrect');
}
return
}
//Validate Product Shiiping Price
if(userShippingPrice === '' ) {
$('#co_productShippingFee').addClass('fielderr');
if ( $('#ps_error, #co_error').hasClass('no') ) {
$('#ps_error, #co_error').removeClass('no');
$('#ps_error').text('This field is required');
$('#co_error').text('Product shipping price field is incorrect');
}
return
}else if ( userShippingPrice < 0 ) {
$('#co_productShippingFee').addClass('fielderr');
if ( $('#ps_error, #co_error').hasClass('no') ) {
$('#ps_error, #co_error').removeClass('no');
$('#ps_error').text('Product Price cannot be a negative value. Kindly enter a valid product price');
$('#co_error').text('Product shipping price field is incorrect');
}
return
}
//Validate Product weight
if( ( productCurrency == 'USD' || productCurrency == 'RMB' ) && is_PhoneProduct == 'No') {
if (userProductWeight === '') {
$('#co-productWeightKG').addClass('fielderr');
if ( $('#pw_error, #co_error').hasClass('no') ) {
$('#pw_error, #co_error').removeClass('no');
$('#pw_error').text('This field is required');
$('#co_error').text('Product weight field is incorrect');
}
return
}else if (productCurrency == 'USD' && is_PhoneProduct == 'No' && userProductWeight < 0.5 ) {
$('#co-productWeightKG').addClass('fielderr');
if ( $('#pw_error, #co_error').hasClass('no') ) {
$('#pw_error, #co_error').removeClass('no');
$('#pw_error').text('The minimum weight is 0.5KG for USA Products/items.');
$('#co_error').text('Product weight field is incorrect');
}
return
}else if (productCurrency == 'RMB' && is_PhoneProduct == 'No' && is_ExpressDelivery == 'Yes' && userProductWeight < 5 ) {
$('#co-productWeightKG').addClass('fielderr');
if ( $('#pw_error, #co_error').hasClass('no') ) {
$('#pw_error, #co_error').removeClass('no');
$('#pw_error').text('The minimum weight is 5KG for China Products/items.');
$('#co_error').text('Product weight field is incorrect');
}
return
}else if (productCurrency == 'RMB' && is_PhoneProduct == 'No' && is_ExpressDelivery == 'No' && userProductWeight < 5 ) {
$('#co-productWeightKG').addClass('fielderr');
if ( $('#pw_error, #co_error').hasClass('no') ) {
$('#pw_error, #co_error').removeClass('no');
$('#pw_error').text('The minimum weight is 5KG for China Products/items.');
$('#co_error').text('Product weight field is incorrect');
}
return
}
}
if( ( productCurrency == 'USD' || productCurrency == 'RMB' ) && is_PhoneProduct == 'Yes') {
if (userProductWeight === '' || userProductWeight == 0 ) {
var userProductWeightS = '1';
}
}
$('#co-submit').val('Please Wait...');
$('#co-submit').attr('disabled', 'disabled');
$('#co_currency').attr('disabled', 'disabled');
$("#co_form :input").prop("disabled", true);
$("#spinner").addClass('processing');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
productTitle : userProductTitle,
productURL : userProductURL,
productPrice : userProductPrice,
shippingPrice : userShippingPrice,
productWeight : userProductWeightS,
coCurrency : productCurrency,
productCategory : productCategory,
userID : userWhoSubmittedForm,
is_Phone : is_PhoneProduct,
is_Amazon : is_AmazonProduct,
is_Express : is_ExpressDelivery,
action : 'customOrder_Send_the_Order'
},
error : function( response ){
},
success : function( response ){
if ( response > 1 ) {
setTimeout(function() {
$('#co-submit').val('Place Your Order');
$('#co-submit').removeAttr('disabled');
$('#co_currency').removeAttr('disabled');
$("#co_form :input").prop("disabled", false);
$(':input','#co_form')
.not(':button, :submit, :reset, :hidden, #co_currency')
.val('')
.prop('checked', false);
$("#spinner").removeClass('processing');
if ( $('#co_dWeight, #is_express').hasClass('no_weight') ) {
$('#co_dWeight, #is_express').removeClass('no_weight');
}
if ( $('#co_success').hasClass('no') ) {
$('#co_success').removeClass('no');
$('#co_success').text('Your Custom Order has been created and added to cart. You\'d be redirect to cart now to complete your order.');
}
}, 500);
}
}
});
});
});
Я использовал Ajax в форме для создания заказа, и когда я добавил код в приведенных выше вопросах, как этот;
add_action( 'wp_ajax_nopriv_customOrder_Send_the_Order', 'CustomOrder_Details_Callback' );
add_action( 'wp_ajax_customOrder_Send_the_Order', 'CustomOrder_Details_Callback' );
add_action('woocommerce_thankyou', 'CustomOrder_Details_Callback')
function CustomOrder_Details_Callback( $order_id ) {
//Get All Value from Ajax
$pTitle = wp_strip_all_tags( $_POST['productTitle'] );
$pLink = wp_strip_all_tags( $_POST['productURL'] );
$pPrice = wp_strip_all_tags( $_POST['productPrice'] );
$pShippingPrice = wp_strip_all_tags( $_POST['shippingPrice'] );
$pWeight = wp_strip_all_tags( $_POST['productWeight'] );
$currency = wp_strip_all_tags( $_POST['coCurrency'] );
$productCat = wp_strip_all_tags( $_POST['productCategory'] );
$coUserID = wp_strip_all_tags( $_POST['userID'] );
$is_PhonePro = wp_strip_all_tags( $_POST['is_Phone'] );
$is_AmazonPro = wp_strip_all_tags( $_POST['is_Amazon'] );
$is_ExpressShip = wp_strip_all_tags( $_POST['is_Express'] ); the product creation below
function get_product_category_by_id( $category_id ) {
$term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
return $term['name'];
}
$product_CO_terms = get_product_category_by_id( 15 );
$post = array(
'post_author' => $coUserID,
'post_status' => "publish",
'post_excerpt' => $pProduct_excerpt,
'post_title' => $pTitle,
'post_type' => "product",
);
//create product for product ID
$product_id = wp_insert_post( $post );
//type of product
wp_set_object_terms($product_id, 'simple', 'product_type');
//Which Category
wp_set_object_terms( $product_id, $product_CO_terms, 'product_cat' );
//setting Shipping class
wp_set_post_terms( $product_id, array($pShipping_Class), 'product_shipping_class' );
//add product meta
update_post_meta( $product_id, '_regular_price', $productPrice_converted );
update_post_meta( $product_id, '_price', $productPrice_converted );
update_post_meta( $product_id, '_weight', $pWeight );
update_post_meta( $product_id, '_store_product_uri', $pLink );
update_post_meta( $product_id, '_visibility', 'visible' );
update_post_meta( $product_id, '_stock_status', 'instock' );
update_post_meta( $product_id, '_list_of_stores', 'custom-order' );
set_post_thumbnail( $product_id, 245 );
//get woocommerce shortcode for add to cart
$found = false;
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
/**************/
/*****THIS IS THE PART I HAVE PROBLEM WITH*********/
/**************/
//get order ID
$order = new WC_Order( $order_id );
//grab items from the order id
$items = $order->get_items();
//loop thru all products in the order section and get product ID
foreach ( $items as $item ) {
$product_id = $item['product_id'];
//choose whatever suites you, trash the product is what I picked
//permanently deletes product
//wp_delete_post($product_id);
//trashes post
wp_trash_post($product_id);
}
/**************/
/*****THE PART I HAVE PROBLEM WITH ENDS HERE*********/
/**************/
if ( $product_id > 1 ) {
echo $product_id;
}else {
echo '0';
}
die();
}
, но когда я сделал это вышеуказанным способом, я получилмного ошибок уведомления о неопределенных переменных, которые используются для создания поста.Я думаю, что это не правильный путь.Поэтому я хотел бы проверить, принадлежит ли продукт к категории ($product_CO_terms
возвращает идентификатор для категории), и если заказ, связанный с продуктом (ами) в категории, завершен, то продукт должен быть удален или удален.
Спасибо