I want to generate woocommerce coupon code dynamically.
My requirements is that after complete the order automatically generate one coupon code in admin side woocommerce coupon code list for particular product.
So any one know my above requirement solutions then please help me.
Thanks,
Ketan.
You can used woocommerce_order_status_completed action hook for order complete. and create post with post type shop_coupon for coupan using wp_insert_post. check below code
function action_woocommerce_order_status_completed( $order_id ) {
$order = wc_get_order( $order_id );
$order_items = $order->get_items();
// Iterating through each item in the order
$item_quantity=0;
foreach ($order_items as $item_id => $item_data) {
$item_quantity=$order->get_item_meta($item_id, '_qty', true);
if($item_quantity>1){
$product_ids[]=$item_data['product_id'];
$coupon_code = 'UNIQUECODE'.$order_id.$item_id; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids',$product_ids );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
unset($product_ids);
}
}
};
// add the action
add_action( 'woocommerce_order_status_completed', 'action_woocommerce_order_status_completed', 10, 1 );
Write a function which will fire when an order has been completed or placed using the woocommerce_order_status_completed or woocommerce_order_status_processing hook. Inside the function, use wp_insert_post to create a post of type shop_coupon. Using wp_insert_post, you can specify the title of the coupon, amount etc.
Related
I add coupons at woocommerce with this code programmatically.
if(empty($coupon_post)){
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
update_post_meta( $new_coupon_id, 'exclude_sale_items', 'no' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
update_post_meta( $new_coupon_id, 'product_categories', '' );
update_post_meta( $new_coupon_id, 'exclude_product_categories', '' );
update_post_meta( $new_coupon_id, 'minimum_amount', '' );
update_post_meta( $new_coupon_id, 'customer_email', '' );
}
But it says always the usage_limit = 1.
I add additional this code to update:
add_action( 'save_post_shop_coupon', 'my_child_after_coupon_save', 10, 3 );
function my_child_after_coupon_save( $post_id, $post, $update ) {
update_post_meta( $post_id, 'usage_limit', '');
}
But it doesn't work first.But if I open the coupon in the backend and update without any changes. The usage limit is set to unlimited.
How can trigger this, that I needn't to open all coupons.
Since WooCommerce 3, your code is a bit outdated as for example apply_before_tax is not used anymore. You should better use all available WC_Coupon setter methods, for coupon creation.
In the code below I just use the necessary setter methods (related to your code):
// Get an empty instance of the WC_Coupon Object
$coupon = new WC_Coupon();
// Set the necessary coupon data (since WC 3+)
$coupon->set_code( $coupon_code ); // (string)
// $coupon->set_description( $description ); // (string)
$coupon->set_discount_type( $discount_type ); // (string)
$coupon->set_amount( $coupon_amount ); // (float)
// $coupon->set_date_expires( $date_expires ); // (string|integer|null)
// $coupon->set_date_created( $date_created ); // (string|integer|null)
// $coupon->set_date_modified( $date_created ); // (string|integer|null)
// $coupon->set_usage_count( $usage_count ); // (integer)
$coupon->set_individual_use( true ); // (boolean)
// $coupon->set_product_ids( $product_ids ); // (array)
// $coupon->set_excluded_product_ids( $excl_product_ids ); // (array)
$coupon->set_usage_limit( 0 ); // (integer)
// $coupon->set_usage_limit_per_user( $usage_limit_per_user ); // (integer)
// $coupon->set_limit_usage_to_x_items( $limit_usage_to_x_items ); // (integer|null)
// $coupon->set_free_shipping( $free_shipping ); // (boolean) | default: false
// $coupon->set_product_categories( $product_categories ); // (array)
// $coupon->set_excluded_product_categories( $excl_product_categories ); // (array)
// $coupon->set_exclude_sale_items( $excl_sale_items ); // (boolean)
// $coupon->set_minimum_amount( $minimum_amount ); // (float)
// $coupon->set_maximum_amount( $maximum_amount ); // (float)
// $coupon->set_email_restrictions( $email_restrictions ); // (array)
// $coupon->set_used_by( $used_by ); // (array)
// $coupon->set_virtual( $is_virtual ); // (array)
// Create, publish and save coupon (data)
$coupon->save();
Now to update coupons you can use the following hooked function with any setter method like:
add_action( 'woocommerce_coupon_options_save', 'action_coupon_options_save', 10, 2 );
function action_coupon_options_save( $post_id, $coupon ) {
$coupon->set_usage_limit( 0 );
$coupon->save();
}
Code goes in functions.php file of the active child theme (or active theme).
I am trying to display a custom admin order column in WooCommerce and I am having a hard time getting the code right here.
I have this code:
add_filter( 'woocommerce_admin_order_data_after_order_details', 'display_order_data_in_admin', 10, 1);
function display_order_data_in_admin( $output )
global $wp_query
$output .= wc_product_dropdown_categories( array(
'show_option_none' => 'Filter by Location',
'taxonomy => 'product_tag',
'name' => 'product_tag',
'selectd' => isset( $wp_query->query_vars['product_tag'] ) ? $wp_query->vars['procut_tag'] :
) );
return $output;
}
I am having a hard time displaying a column for filtering my orders by location that has been selected in checkout.
add_filter( 'manage_edit-shop_order_columns', 'wc_add_new_order_admin_list_column' );
function wc_add_new_order_admin_list_column( $columns ) {
$columns['billing_country'] = 'Country';
return $columns;
}
add_action( 'manage_shop_order_posts_custom_column', 'wc_add_new_order_admin_list_column_content' );
function wc_add_new_order_admin_list_column_content( $column ) {
global $post;
if ( 'billing_country' === $column ) {
$order = wc_get_order( $post->ID );
echo $order->get_billing_country();
}
}
I have using this function code to make new Custom Text Area, but have issue to show it in product page.
// Custom Field Product
add_action( 'woocommerce_product_options_general_product_data',
'woo_add_custom_general_fields' );
add_action( 'woocommerce_process_product_meta',
'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_textarea_input(
array(
'id' => '_textarea',
'label' => __( 'Custom Text:', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Enter the custom value here.', 'woocommerce' )
)
);
echo '</div>';
}
// Save Changes to DB
function woo_add_custom_general_fields_save( $post_id ){
// Textarea
$woocommerce_textarea = $_POST['_textarea'];
if( !empty( $woocommerce_textarea ) )
update_post_meta( $post_id, '_textarea', esc_html( $woocommerce_textarea
) );
}
// Show data to product
add_action( 'woocommerce_after_add_to_cart_button',
'custom_content_after_addtocart_button', 100 );
function custom_content_after_addtocart_button() {
// custom content.
echo get_post_meta( $post->ID, '_textarea', true );
}
Looks like when press save, its storing data in DB, but its not showing in single product page. Can someone to tell me where is issue in this function?
The problem is that in the following function, $post is not defined. (The code was indented for clarity.)
// Show data to product
add_action( 'woocommerce_after_add_to_cart_button',
'custom_content_after_addtocart_button', 100 );
function custom_content_after_addtocart_button() {
// custom content.
echo get_post_meta( $post->ID, '_textarea', true );
}
So, a simple fix would be to add global $post; to the function:
// Show data to product
add_action( 'woocommerce_after_add_to_cart_button',
'custom_content_after_addtocart_button', 100 );
function custom_content_after_addtocart_button() {
global $post;
// custom content.
if ( $post ) {
echo get_post_meta( $post->ID, '_textarea', true );
}
}
Alternatively, you can use the global $product object:
// Show data to product
add_action( 'woocommerce_after_add_to_cart_button',
'custom_content_after_addtocart_button', 100 );
function custom_content_after_addtocart_button() {
global $product;
// custom content.
if ( $product ) {
echo get_post_meta( $product->get_id(), '_textarea', true );
}
}
I am trying to add a custom metabox in woocommerce. It has been added perfectly. My ultimate goal is to call that custom field in a function and show it in the cart.php. So I coded :
For Custom field: [I would refer http://www.remicorson.com/mastering-woocommerce-products-custom-fields/] in this regard
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input(
array(
'id' => 'number_field',
'label' => __( '<strong style="color:#239804">Your Free Products</strong>', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Please enter a number', 'woocommerce' ),
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
echo '</div>';
}//woo_add_custom_general_fields
function woo_add_custom_general_fields_save( $post_id ){
$woocommerce_number_field = $_POST['number_field'];
if( !empty( $woocommerce_number_field ) )
update_post_meta( $post_id, 'number_field', esc_attr( $woocommerce_number_field ) );
}//woo_add_custom_general_fields_save( $post_id )
It has perfectly fitted in the Product Admin Page. Now I am creating another function where I am creating a counter for cart.php
function free_products(){
global $woocommerce ,$product, $post;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$free_number = get_post_meta( $post->ID, 'number_field', true );
$free_product = $cart_item['quantity'] * $free_number;
echo apply_filters( 'woocommerce_cart_item_quantity', $free_product, $cart_item_key );
}
}
In My cart.php when I add
<td class="product-quantity">
<?php
echo free_products();
?>
</td>
The output become zero in front end. Can anyone please help me what I am going wrong. Thanks in advance.
Try below code :
function free_products(){
global $woocommerce ,$product, $post;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$my_var = $cart_item['product_id'];
$free_number = get_post_meta( $my_var, 'number_field', true );
$free_product = $cart_item['quantity'] * $free_number;
echo apply_filters( 'woocommerce_cart_item_quantity', $free_product);
}
}
Let me know if It is working for you or not.Its working for me.
I m trying to add the first link from the post content to a custom field. Something is wrong and I ve been trying to get it to work but no luck. What should I do to add the link to "link" custom field?
add_action( 'publish_post', 'check_post' );
function check_post( $post_id ) {
$user_info = get_userdata(1);
function get_first_link() {
global $post, $posts;
preg_match_all('/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $links);
return $links[1][0];
}
$first_link = get_first_link();
add_post_meta($post_id, 'link', $first_link, true);
add_post_meta($post_id, 'users', $user_info->user_login, true);
}
EDIT
I got it working halfway. It saves the url, but it doesn't save it when the post is published. It saves it on update. What do I need to use? I tried using publish_post but that saved the url on update also.
add_action( 'save_post', 'my_save_post', 10, 2 );
function my_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) )
return;
$matches = array();
preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $matches );
$first_link = false;
if ( ! empty( $matches[1][0] ) )
$first_link = $matches[1][0];
$user_info = get_userdata(1);
$meta_link = $_POST['link'];
$args = array(
'post__not_in'=> array($id),
'post_type' => 'post',
'post_status' => array('publish'),
'meta_query' => array(
array(
'key' => 'link',
'value' => $first_link,
'compare' => '='
)
)
);
$existingMeta = get_posts( $args );
if(empty($existingMeta)){
//Go ahead and save meta data
update_post_meta( $post_id, 'link', esc_url_raw( $first_link ) );
update_post_meta($post_id, 'users', $user_info->user_login);
}else{
//Revert post back to draft status
update_post_meta( $post_id, 'link', $existingMeta[0]->ID );
update_post_meta($existingMeta[0]->ID, 'users', $user_info->user_login);
//Now perform checks to validate your data.
//Note custom fields (different from data in custom metaboxes!)
//will already have been saved.
$prevent_publish= true;//Set to true if data was invalid.
if ($prevent_publish) {
// unhook this function to prevent indefinite loop
remove_action('save_post', 'my_save_post');
// update the post to change post status
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
}
}
}
Here you go:
add_action( 'save_post', 'my_save_post', 10, 2 );
function my_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) )
return;
$matches = array();
preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $matches );
$first_link = false;
if ( ! empty( $matches[1][0] ) )
$first_link = $matches[1][0];
update_post_meta( $post_id, 'link', esc_url_raw( $first_link ) );
}