display wordpress post meta in editor after save - php

I am trying to write a small plugin in wordpress, I have a small meta box with text input and a radio button in which user needs to add information, and I want that the imformation that is saved in the post meta box will be displayed after save (in the current state the input text resets to the default plaholder after save).
this is the relevant code:
add_action( 'add_meta_boxes', 'asset_price' );
function asset_price() {
add_meta_box(
'asset_price',
__( 'asset price', 'myplugin_textdomain' ),
'asset_price_box_content',
'asset',
'normal',
'high'
);
}
function asset_price_box_content( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'asset_price_box_content_nonce' );
echo '<label for="asset_price"></label>
<input type="text" id="asset_price" name="asset_price" placeholder="insert price" />
<input type="radio" name="currency" value="percent" checked="checked">%
<input type="radio" name="currency" value="Dollar">$';
}
add_action( 'save_post', 'asset_price_box_save' );
function asset_price_box_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
if ( !wp_verify_nonce( $_POST['asset_price_box_content_nonce'], plugin_basename( __FILE__ ) ) )
return $post_id;
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
$old = get_post_meta($post_id, "asset_price", true);
$new = $_POST["asset_price"];
if ($new && $new != $old) {
$product_price = $_POST['asset_price'];
update_post_meta( $post_id, 'asset_price', $product_price );
} elseif ('' == $new && $old) {
delete_post_meta($post_id, "asset_price", $old);
}
}
Thanks in advance

You can get the meta box value using get_post_meta() function and display it in the textbox
function asset_price_box_content( $post ) {
$price = get_post_meta($post->ID, "asset_price", true);
wp_nonce_field( plugin_basename( __FILE__ ), 'asset_price_box_content_nonce' );
echo '<label for="asset_price"></label>
<input type="text" id="asset_price" name="asset_price" placeholder="insert price" value="'.$price.'" />
<input type="radio" name="currency" value="percent" checked="checked">%
<input type="radio" name="currency" value="Dollar">$';
}

Related

Display categories of a Custom post type in WooCommerce product

I have created a custom post type with own categories.
I would like to link the categories of the custom post type to the WooCommerce product. e.g. This product belongs to the category Fabric cover.
These categories I have displayed in Woocommerce products in the backend.
I do that with getterm. So far, everything works. I then created a checkbox field in front of each category.
When I save the contents, all categories are stored in an array (whether I've selected it or not). I would like to save only the category I have selected. What am I doing wrong?
how can I just save the array of the selected checkbox in metabox (pro_in_cat_fields).
At the moment all values are saved. If I only check one checkbox (for example, fabric cover1), only the values that are in the same array of the checkbox need to be saved. not the values of fabric cover 1, fabric cover 2, ... etc
<?php
add_action('admin_init', 'add_pro_in_cat_boxes', 1);
function add_pro_in_cat_boxes() {
add_meta_box( 'pro_in_cat-fields', 'Save product in custom category', 'pro_in_cat_meta_box_display', 'product', 'normal', 'low');
}
function pro_in_cat_meta_box_display() {
global $post;
$pro_in_cat_fields = get_post_meta($post->ID, 'pro_in_cat_fields', true);
wp_nonce_field( 'pro_in_cat_meta_box_nonce', 'pro_in_cat_meta_box_nonce' );
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.pro_in_cat_submit').click(function(e) {
e.preventDefault();
$('#publish').click();
});
});
</script>
<table id="pro_in_cat-fieldset-one" width="100%">
<thead>
<tr>
<th width="30%"></th>
<th width="70%"></th>
</tr>
</thead>
<tbody>
<?php
$stoffcat_parent= get_terms( 'cover_cat', array( 'hide_empty' => false, 'parent' => 0 ) );
if ( $stoffcat_parent ) :
foreach( $stoffcat_parent as $parent_term ) {
echo $parent_term->name . '<br>';
$stoffcat_value = get_terms( 'cover_cat', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) );
foreach( $stoffcat_value as $child_term ) {
?>
<tr>
<td>
<input type="checkbox" class="widefat" name="pro_in_cat_status[]" value="<?php echo $checked; ?>" />
<input type="text" class="widefat" name="pro_in_cat_name[]" value="<?php if($child_term->name != '') echo esc_attr( $child_term->name ); ?>" /></td>
<td><input type="text" class="widefat" name="pro_in_cat_termid[]" value="<?php if($child_term->term_id != '') echo esc_attr( $child_term->term_id ); ?>" />
<input type="text" class="widefat" name="pro_in_cat_slug[]" value="<?php if($child_term->slug != '') echo esc_attr( $child_term->slug); ?>" /></td>
</tr>
<?php
}
}
else :
// show a blank one
?>
<tr>
<td><input type="checkbox" class="widefat" name="pro_in_cat_status[]" />
<input type="text" class="widefat" name="pro_in_cat_name[]" /></td>
<td><input type="text" class="widefat" name="pro_in_cat_termid[]" /><input type="text" class="widefat" name="pro_in_cat_slug[]" /></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<p>
<input type="submit" class="pro_in_cat_submit" value="Save" />
</p>
<?php
}
add_action('save_post', 'pro_in_cat_meta_box_save');
function pro_in_cat_meta_box_save($post_id) {
if ( ! isset( $_POST['pro_in_cat_meta_box_nonce'] ) ||
! wp_verify_nonce( $_POST['pro_in_cat_meta_box_nonce'], 'pro_in_cat_meta_box_nonce' ) )
return;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (!current_user_can('edit_post', $post_id))
return;
$pro_in_catold = get_post_meta($post_id, 'pro_in_cat_fields', true);
$pro_in_catnew = array();
$pro_in_catstatus = $_POST['pro_in_cat_status'];
$pro_in_catnames = $_POST['pro_in_cat_name'];
$pro_in_cattermid = $_POST['pro_in_cat_termid'];
$pro_in_catslug = $_POST['pro_in_cat_slug'];
$count = count( $pro_in_catnames );
for ( $i = 0; $i < $count; $i++ ) {
if ( $pro_in_catstatus[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_status'] = stripslashes( strip_tags( $pro_in_catstatus[$i] ) );
}
if ( $pro_in_catnames[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_name'] = stripslashes( strip_tags( $pro_in_catnames[$i] ) );}
if ( $pro_in_cattermid[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_termid'] = stripslashes( strip_tags( $pro_in_cattermid[$i] ) );}
if ( $pro_in_catslug[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_slug'] = stripslashes( strip_tags( $pro_in_catslug[$i] ) );}
}
if ( !empty( $pro_in_catnew ) && $pro_in_catnew != $pro_in_catold )
update_post_meta( $post_id, 'pro_in_cat_fields', $pro_in_catnew );
elseif ( empty($pro_in_catnew) && $pro_in_catold )
delete_post_meta( $post_id, 'pro_in_cat_fields', $pro_in_catold );
}

Kindly help to change input type text to radio from the PHP code

I'm trying to add and change the input type from text to radio button to use in my wordpress theme user profile settings like Gender: Male Female, but can't do the trick in the code. don't know how to change it.
tried with some code from w3schools given below, but that doesn't work too.
Tried radio type, but doesn't work
<label><?php _e( 'gender', 'themer' ); ?></label>
<input type="radio" name="user_new_field" <?php if (isset($new_field) && $new_field=="female") echo "checked";?> value="female">Female
<input type="radio" name="user_new_field" <?php if (isset($new_field) && $new_field=="male") echo "checked";?> value="male">Male
</div>
i have to change the code to radio type, gonna use them in wordpress functions.php
add_action( 'themer_after_user_profile_registration_fields_action', 'wpt_show_user_profile_custom_inputs' );
function wpt_show_user_profile_custom_inputs( $uid ) {
$user_new_field = get_user_meta( $uid, 'user_new_field', true );
$new_field = empty( $_POST['user_new_field'] ) ? $user_new_field : stripslashes( $_POST['user_new_field'] ); ?>
<div class="field">
<label><?php _e( 'gender', 'themer' ); ?></label>
<input type="text" value="<?php echo $new_field; ?>" name="user_new_field" size="40" placeholder="<?php echo _x( 'My New Field Placeholder', 'Placeholder for: New field', 'themer' ); ?>" />
</div>
<?php }
// Save the field value from user settings page
add_action( 'themer_user_profile_extra_fields_update', 'wpt_save_user_profile_custom_inputs' );
function wpt_save_user_profile_custom_inputs( $uid ) {
if ( isset( $_POST['save-info'] ) ) {
if ( isset( $_POST['user_new_field'] ) ) {
update_user_meta( $uid, 'user_new_field', $_POST['user_new_field'] );
}
}
}
You can do this by replacing your code with below code in functions.php
add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );
function extra_user_profile_fields( $user ) { ?>
<h3><?php _e("Extra Field", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label ><?php _e("Gender"); ?></label></th>
<td>
<input type="radio" name="gender" id="gender" value="male" <?php if(esc_attr( get_the_author_meta( 'gender', $user->ID ) ) == 'male'){echo ' checked '; } ?>class="regular-text" />Male
<input type="radio" name="gender" id="gender" value="female" <?php if(esc_attr( get_the_author_meta( 'gender', $user->ID ) ) == 'female'){echo ' checked '; } ?> class="regular-text" />Female
<br />
<span class="description"><?php _e("Please enter your gender."); ?></span>
</td>
</tr>
</table>
<?php }
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'gender', $_POST['gender'] );
}

How to delete a product that belongs to a category when its order is completed in woocommerce

I need to figure out how to delete a product(s) from a particular category when the order associated to it is completed (marked as completed) in WooCommerce.
Below is how the product is setup. users are allowed to create a product from frontend and when the product/products are created, it is assigned to a specific category. After purchase by user, an order is assigned to the product(s).
Now i want to be able to delete the product automatically when the order assigned to the product(s) is completed.
I have checked this question (How Can I remove a particular product from an completed order in woocommerce?) but doesn't help me, as well as this question (Add Woocommerce Temporary product)
Below is the HTML Code for the front end form
<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>
and Below is the jQuery Code which is used to validate the form and send the data via 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);
}
}
});
});
});
I used Ajax on the form to create the order and when i added the code in the above questions like this;
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();
}
but when i did it in the above way i got a lot of notice error regarding undefined variables which is used for the post creation. I think its not the right way to go about this. So i would like to check if a product belongs to the category ($product_CO_terms returns the ID for the category) and if the order associated to the product(s) in the category is completed, then the product should be trashed or deleted.
Thanks

How to get Text Area in WordPress posts section?

I need to change this code to implement "More info" field as a text field in my WordPress post section.
The "More info" field looks like this:
I use smartmetabox. It has 2 files:
textarea.php:
<textarea name="<?php echo $id?>" id="<?php echo $id?>" rows="5" cols="100" class="custom"><?php echo $value?></textarea>
text.php:
<input type="text" name="<?php echo $id?>" id="<?php echo $id?>" value="<?php echo $value?>" class="regular-text" />
And my_file.php code is:
<?php
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', __('Information', 'addict'), 'cd_meta_box_cb', 'post', 'normal', 'high' );
}
function cd_meta_box_cb( $post )
{
$values = get_post_custom( $post->ID );
$creteria_1_text = isset( $values['creteria_1_text'] ) ? esc_attr( $values['creteria_1_text'][0] ) : '';
$check = isset( $values['my_meta_box_check'] ) ? esc_attr( $values['my_meta_box_check'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<label for="creteria_1_text"><b><?php _e("More info, 'addict') ?></b></label>
<input style="width:85%" type="text" name="creteria_1_text" id="creteria_1_text" value="<?php echo $creteria_1_text; ?>" />
</p>
<?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchords can only have href attribute
)
);
// Probably a good idea to make sure your data is set
if( isset( $_POST['creteria_1_text'] ) )
update_post_meta( $post_id, 'creteria_1_text', wp_kses( $_POST['creteria_1_text'], $allowed ) );
}
// function for show rating content
//$key_1_value = get_post_meta($post->ID, 'my_meta_box_text', true);
?>
After some digging i found that i should replace this code:
<input style="width:85%" type="text" name="creteria_1_text" id="creteria_1_text" value="<?php echo $creteria_1_text; ?>
To:
<textarea name="creteria_1_text" id="creteria_1_text" rows="5" cols="100" class="custom"><?php echo $creteria_1_text; ?></textarea>

Get the value from a custom field in category

I made a custom field in admin category interface named custom order. It is showing in the admin. But now I am having difficulties in getting the information from the field and echo it in index.php.
If I run
$thisCat = get_category( 29);
print_r($thisCat);
I don't get any information from the custom field.
echo get_post_custom_values('category_custom_order', 29); doesn't echo anything.
How should I get the value from category_custom_order?
Here is my code for custom field in functions.php:
<?php
/** Add Custom Field To Category Form */
add_action( 'category_add_form_fields', 'category_form_custom_field_add', 10 );
add_action( 'category_edit_form_fields', 'category_form_custom_field_edit', 10, 2 );
function category_form_custom_field_add( $taxonomy ) {
?>
<div class="form-field">
<label for="category_custom_order">Custom Order</label>
<input name="category_custom_order" id="category_custom_order" type="text" value="" size="40" aria-required="true" />
<p class="description">Enter a custom order value.</p>
</div>
<?php
}
function category_form_custom_field_edit( $tag, $taxonomy ) {
$option_name = 'category_custom_order_' . $tag->term_id;
$category_custom_order = get_option( $option_name );
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="category_custom_order">Custom Order</label></th>
<td>
<input type="text" name="category_custom_order" id="category_custom_order" value="<?php echo esc_attr( $category_custom_order ) ? esc_attr( $category_custom_order ) : ''; ?>" size="40" aria-required="true" />
<p class="description">Enter a custom order value.</p>
</td>
</tr>
<?php
}
/** Save Custom Field Of Category Form */
add_action( 'created_category', 'category_form_custom_field_save', 10, 2 );
add_action( 'edited_category', 'category_form_custom_field_save', 10, 2 );
function category_form_custom_field_save( $term_id, $tt_id ) {
if ( isset( $_POST['category_custom_order'] ) ) {
$option_name = 'category_custom_order_' . $term_id;
update_option( $option_name, $_POST['category_custom_order'] );
}
}
You should be able to get it this way, and by the way it's not a custom field but an option.
$category_id = 29;
$category_custom_order = get_option( 'category_custom_order_' . $category_id );
echo $category_custom_order;

Categories