How to read array structure and get certain data in Php - php

I want to get the product_id,variation_id,and quantity from this cart array. By the way this cart array was return by woocommerce get_cart function. How do I read this array in Php so I can get the data? I need those 3 data to create an order with it.
public function get_cart(){
$user_id = 1;
$key = '_woocommerce_persistent_cart';
$single = true;
$carts = get_user_meta($user_id, $key, $single);
return $carts;
}
i have customize order creation code below how can i change it?
public function Order_creation()
{
if ($_REQUEST['dev']) {
$address = array(
'first_name' => 'Zayle',
'last_name' => 'Ong',
'company' => 'Timios',
'email' => 'Crystalize#hotmail.com',
'phone' => '777-777-777-777',
'address_1' => '31 Main Street',
'address_2' => '',
'city' => 'Simei',
'state' => 'SG',
'postcode' => '520151',
'country' => 'Singapore'
);
$userid = 1;
/*
* Example product 1 simple
*/
$pointsEarn = 88;
$products[] = array(
"id" => 9, // id of product
"variation" => '', // id of variaton
"quantity" => 1
) // quantity
;
/*
* Example product variation
*/
$products[] = array(
"id" => 76, // id of product
"variation" => 97, // id of variaton
"quantity" => 2
); // quantity
$products[] = array(
"id" => 76, // id of product
"variation" => 98, // id of variaton
"quantity" => 1
);
$redeemedPoints = 100;
$note = "Test Note";
} else {
$address = array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'company' => $_POST['company'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
'address_1' => $_POST['adddress1'],
'address_2' => $_POST['adddress2'],
'city' => $_POST['city'],
'state' => $_POST['state'],
'postcode' => $_POST['postcode'],
'country' => $_POST['country']
);
$userid = $_POST['userid'];
/*
* POST products should be like
* array(array("id"=>1,"variation"=>"","quantity"),array("id"=>1,"variation"=>"","quantity"=>1),array("id"=>1,"variation"=>"","quantity"=>3))
*/
$pointsEarn = $_POST['PointsEarn'];
$products = $_POST['products'];
$redeemedPoints = $_POST['redeemedPoints'];
$note = $_POST['note'];
if (! $_POST['first_name'] && ! $_POST['last_name'] && ! $_POST['email'] && ! $_POST['adddress1'] & ! $_POST['city']) {
return array(
"error" => "Please fill First name, Last Name, Address and City",
"orderstatus" => "error"
);
}
if (! $userid) {
return array(
"error" => "Need to specify a userid",
"orderstatus" => "error"
);
}
if (! $productid) {
return array(
"error" => "Need to specify a product id",
"orderstatus" => "error"
);
}
if (! $redeemedPoints) {
return array(
"error" => "Need to specify points to use",
"orderstatus" => "error"
);
}
}
$pointsuser = WC_Points_Rewards_Manager::get_users_points($userid);
if ($pointsuser >= $$redeemedPoints) {
$order = wc_create_order();
if (count($products)) {
foreach ($products as $key => $value) {
if ($value['variation']) {
$product = new WC_Product_Variable($value['id']);
$product->variation_id = $value['variation'];
$variation = $product->get_available_variations();
foreach ($variation as $key2 => $value2) {
if ($value2['variation_id'] == $value['variation']) {
$valdata['variation'] = $value2['attributes'];
}
}
$order->add_product($product, $value['quantity'], $valdata);
update_post_meta($value['variation'], "_stock", (get_post_meta($productid, "_stock", true) - $value['quantity']));
} else {
$product = new WC_Product($value['id']);
$order->add_product($product, $value['quantity']);
update_post_meta($value['id'], "_stock", (get_post_meta($productid, "_stock", true) - $value['quantity']));
}
}
}
if (! $product->is_type('variable')) {} else {}
$order->set_address($address, 'billing');
$order->set_address($address, 'shipping');
$discount_code = str_replace("--userid--", $userid, "wc_points_redemption_--userid--_" . date("d-m-Y") . "_" . rand(0, 99999));
/*
* Create coupon
*/
$coupon_code = $discount_code; // Code
$amount = WC_Points_Rewards_Manager::calculate_points_value($redeemedPoints); // 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' => $userid,
'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', '');
update_post_meta($new_coupon_id, 'exclude_product_ids', '');
update_post_meta($new_coupon_id, 'usage_limit', '1');
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');
$order->add_order_note( $note);
$order->add_coupon($discount_code, $amount);
$order->calculate_totals();
$order->set_total($order->calculate_totals() - $amount);
$order->set_total($amount, 'cart_discount');
$orderid = new WC_Order($order->ID);
$order_id = trim(str_replace('#', '', $order->get_order_number()));
add_post_meta($order_id, '_payment_method', 'Pending Payment');
update_post_meta($order_id, '_created_via', 'checkout');
update_post_meta($order_id, '_customer_user', $userid);
add_post_meta($order_id, '_payment_method_title', 'Pending Payment');
update_post_meta($order->id, '_wc_points_redeemed', $redeemedPoints);
WC_Points_Rewards_Manager::decrease_points($userid, $redeemedPoints, 'order-redeem', "coupon " . $coupon_code . " used for order " . $order_id, $order_id);
update_post_meta( $order->id, '_wc_points_earned', $pointsEarn );
WC_Points_Rewards_Manager::increase_points( $order->user_id, $pointsEarn, 'order-placed', null, $order->id );
return array(
"orderid" => $order_id,
"points earn" =>$pointsEarn,
"orderstatus" => "ok"
);
} else {
return array(
"error" => "You do not have enought points",
"orderstatus" => "error"
);
}
}

global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item) {
$products[] = array(
"id" => $item['product_id'], // id of product
"variation" => $item['variation_id'], // id of variaton
"quantity" => $item['quantity']
);
}

Related

WooCommerce - Get product variation SKU in loop

I'm trying to get the product variation SKU's but it always returns blank. I've tried everything I can think of so far and I have been unable to find any answer here.
foreach ($available_variations as $variation) {
$variation_id = $variation->ID;
$variant = new WC_Product_Variation($variation_id);
// Get data from the product variation
$excerpt_var = wpautop($variation['variation_description']);
$sku = $variation['sku'];
$price = $variation['display_regular_price'];
$price = number_format($price, 0, ',', ' ');
if ($price != null) {
$price = $price . ",-";
}
$results[] = array(
"id" => $available_variations,
"cat" => $cat->name,
"sku" => $sku,
"title" => $title,
"price" => $price != null ? $price : "",
"excerpt" => $excerpt_var,
"thumbnail" => $thumbnail,
"type" => "variation"
);
}
Whole function to get all prods and variations is here:
function get_all_prods_for_csv() {
$results = array(); // Rows to be returned
// Settings
$taxonomy = 'product_cat';
$title = '';
$empty = 0;
// Query arguments
$args_cat = array(
'taxonomy' => $taxonomy,
'orderby' => 'menu_order',
'show_count' => 0, // 1 for yes, 0 for no
'pad_counts' => 0, // 1 for yes, 0 for no
'hierarchical' => 0, // 1 for yes, 0 for no
'title_li' => $title,
'hide_empty' => $empty
);
// For all categories
foreach (get_categories( $args_cat ) as $cat) {
// If root category
if ($cat->category_parent === 0) {
$category_id = $cat->term_id;
$category_slug = $cat->slug;
$cat_thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$cat_image = wp_get_attachment_url( $cat_thumbnail_id );
$results[] = array(
"id" => $category_id,
"cat" => $cat->name,
"sku" => '',
"title" => '',
"price" => '',
"excerpt" => category_description( $category_id ),
"thumbnail" => $thumbnail,
"type" => "category"
);
// Get all products for current category
// Query arguments
$args_prod = array(
'post_type' => 'product',
'posts_per_page' => -1,
'order' => 'asc',
'orderby' => 'menu_order',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_id
)
)
);
$products = get_posts( $args_prod );
// For all products
foreach ( $products as $prod ) {
$product = wc_get_product($prod->ID);
// Get data from the product
$title = $product->get_title();
$thumbnail = get_the_post_thumbnail_url($prod->ID);
$excerpt = wpautop($product->get_short_description()); // wpautop(get_the_excerpt($prod->ID));
// If single variation
if( $product->is_type( 'simple' ) ) {
$price = $product->get_price();
$price = number_format($price, 0, ',', ' ');
$results[] = array(
"id" => $prod->ID,
"cat" => $cat->name,
"sku" => $product->get_sku(),
"title" => $title,
"price" => $price != null ? $price . "" : "",
"excerpt" => $excerpt,
"thumbnail" => $thumbnail,
"type" => "simple"
);
} else if ( $product->is_type( 'variable' ) ) {
$available_variations = $product->get_available_variations();
$counting_variations = 1;
foreach ($available_variations as $variation) {
$counting_variations++;
}
$results[] = array(
"id" => $prod->ID,
"cat" => $cat->name,
"sku" => "",
"title" => $title,
"price" => "",
"excerpt" => $excerpt,
"thumbnail" => $thumbnail,
"type" => "variation_root"
);
foreach ($available_variations as $variation) {
$variation_id = $variation->ID;
$variant = new WC_Product_Variation($variation_id);
// Get data from the product variation
$excerpt_var = wpautop($variation['variation_description']);
$sku = $variation['sku'];
$price = $variation['display_regular_price'];
$price = number_format($price, 0, ',', ' ');
if ($price != null) {
$price = $price . ",-";
}
$results[] = array(
"id" => $available_variations,
"cat" => $cat->name,
"sku" => $sku,
"title" => $title,
"price" => $price != null ? $price : "",
"excerpt" => $excerpt_var,
"thumbnail" => $thumbnail,
"type" => "variation"
);
}
}
}
}
}
return $results;
}
This line
$sku = $variation['sku'];
should be
$sku = $variant['sku'];
since you get the object as that variable $variant.

Woocommerce multi Vendor Split Shipping without plugin or custom plugin

I Want To Calculate Shipping Rates and Display WooCommerce Shipping Methods on the Cart & Checkout Page (Either Calculate & Display WooCommerce Shipping Rates Separately for Each Vendor, Or, Add WooCommerce Shipping Cost for Each Vendor, and Display Final Shipping Cost on Cart Page).
There are many plugins available but I want to do it without a plugin(functions.php) or create my own plugin.
$packages[] = array(
'ship_via' => $shipping_method_ids ?: array('flat_rate', 'local_pickup', 'free_shipping'),
'name' => $shipping_class_name,
'contents' => $new_package,
'contents_cost' => array_sum(wp_list_pluck($new_package, 'line_total')),
'applied_coupons' => WC()->cart->applied_coupons,
'destination' => array(
'country' => WC()->customer->get_shipping_country(),
'state' => WC()->customer->get_shipping_state(),
'postcode' => WC()->customer->get_shipping_postcode(),
'city' => WC()->customer->get_shipping_city(),
'address' => WC()->customer->get_shipping_address(),
'address_2' => WC()->customer->get_shipping_address_2()
)
);
I have done create Separate package shipping wise. but I want to create the same (slipt shipping) according to Vendor Wise.
In short
Vendor A -> Shipping(1,2,3..)
Vendor B -> Shipping(1,2,3..)
Vendor C -> Shipping(1,2,3..)
.
.
.
etc...
See screenshoot for more Info.
Finally, we got an answer to this question.
First of all, we should get vendors associated with cart products.
// Get Vendor ID from Prduct ID - Method 1 (Compatible with woocommerce-product-vendors plugin)
function get_product_vendors_1( $product_id = null ) {
if ( null === $product_id ) {
return null;
}
$term = wp_get_object_terms( $product_id, WC_PRODUCT_VENDORS_TAXONOMY, array( 'fields' => 'ids' ) );
if ( is_wp_error( $term ) || empty( $term ) ) {
return null;
}
return $term[0];
}
// Get Vendor ID from Prduct ID - Method 2
function get_user_roles_by_user_id( $user_id = null, $role = array('vendors') ) {
$user = get_userdata( $user_id );
$user_roles = array_intersect($user->roles,$role);
if (isset($user_roles) && !empty($user_roles)) {
return $user_id;
}
return false;
}
function get_product_vendors_2($product_id = null){
// Vendors roles - you can change accordingly
$role = array(
'wc_product_vendors_pending_vendor',
'wc_product_vendors_manager_vendor',
'wc_product_vendors_admin_vendor'
);
$user_id = get_post_field( 'post_author', $product_id );
if(get_user_roles_by_user_id( $user_id, $role)){
return $user_id;
}
return false;
}
// Now you can use one of them
get_product_vendors_1($product_id)
or
get_product_vendors_2($product_id)
Now Multi-Vendor Split Shipping full Source code.
add_filter('woocommerce_cart_shipping_packages', 'woo_multi_vendors_shipping_packages');
function woo_multi_vendors_shipping_packages($packages)
{
$i = 1;
$packages = $vendor_items_map = array();
foreach (WC()->cart->get_cart() as $cart_item)
{
if ($cart_item['data']->needs_shipping())
{
$product_id = $cart_item['product_id'];
// Get vendors for each product.
// $vendor = get_product_vendors_2( $product_id);
$vendor = get_product_vendors_1( $product_id);
$vendor_id = isset($vendor) ? (int)$vendor : 0;
$vendor_items_map[$vendor_id][] = $cart_item;
}
}
foreach($vendor_items_map as $vendor_id => $vendor_items) {
if(!empty($vendor_items)){
$packages_name = null;
if($vendor_id){
$user_displayname = get_term($vendor_id)->name ?: '';
if($user_displayname){
$packages_name = '<span class="ship-name">Shipping #'.$i.'</span><span class="vendor-name">'.$user_displayname.'</span>';
}
}
$packages[] = array(
//'ship_via' => array( 'flat_rate' ),
'name' => $packages_name ?: null,
'contents' => $vendor_items,
'contents_cost' => array_sum( wp_list_pluck( $vendor_items, 'line_total' ) ),
'applied_coupons' => WC()->cart->applied_coupons,
'destination' => array(
'country' => WC()->customer->get_shipping_country(),
'state' => WC()->customer->get_shipping_state(),
'postcode' => WC()->customer->get_shipping_postcode(),
'city' => WC()->customer->get_shipping_city(),
'address' => WC()->customer->get_shipping_address(),
'address_2' => WC()->customer->get_shipping_address_2()
)
);
}
$i++;
}
return $packages;
}

Woocommerce in stock Notifier Api

i am using in stock notifier plugin https://wordpress.org/plugins/back-in-stock-notifier-for-woocommerce/
in this plugin rest api or plugin of rest api not given
i am making custom rest api plugin and insert data in a table but email not coming during subscription of email id
and during in stock of product.
my custom code for instock api
<?php
/**
* Plugin Name: Very First Plugin
* Plugin URI: https://www.yourwebsiteurl.com/
* Description: This is the very first plugin I ever created.
* Version: 1.0
* Author: Your Name Here
* Author URI: http://yourwebsiteurl.com/
**/
/**
* Grab latest post title by an author!
*
* #param array $data Options for the function.
* #return string|null Post title for the latest,
 * or null if none.
*/
/*
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/authorsss/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
*/
function my_awesome_func( $data ) {
global $wpdb;
if($data['cwginstock_user_id']==''){
$students_arr = array(
"responseCode" => 400,
"responseMessage" => "Please enter user id.",);
echo json_encode($students_arr);
}elseif($data['cwginstock_subscriber_email'] == ''){
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter email id.",);
echo json_encode($students_arr);
}elseif($data['cwginstock_pid'] == ''){
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter product id.",);
echo json_encode($students_arr);
}else{
$tablename2 = $wpdb->prefix . "posts";
//himanshu-swamiitechs-co-in__trashed
$ok = str_replace(".","",$data['cwginstock_subscriber_email']);
$post_name = str_replace("#","-",$ok);
$res = $wpdb->insert(
$tablename2,
array(
'post_author' => $data['cwginstock_user_id'],
'post_content' => "",
'post_title' => $data['cwginstock_subscriber_email'],
'post_excerpt' => "",
'post_name'=>$post_name,
'post_status' =>'cwg_subscribed',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => "",
'to_ping' => "",
'pinged' => "",
'post_content_filtered' =>'',
'post_parent' =>'',
//'guid' => 'http://localhost/ecommerces4/cwginstocknotifier/himanshu-swamiitechs-co-in/',
'guid' => 'http://localhost/ecommerces4/cwginstocknotifier/'.$post_name.'/',
"menu_order"=> 0,
"post_type"=> "cwginstocknotifier",
"post_mime_type" =>"",
"comment_count"=> 0,
"post_date"=>Date('Y-m-d H:i:s'),
"post_date_gmt"=>Date('Y-m-d H:i:s'),
"post_modified_gmt" =>Date('Y-m-d H:i:s'),
"post_modified"=>Date('Y-m-d H:i:s')
)
);
$lastid = $wpdb->insert_id;
$data1 = array(
'cwginstock_variation_id',
'cwginstock_subscriber_email',
'cwginstock_user_id',
'cwginstock_language',
'cwginstock_pid'
);
$data3 = array(0, $data['cwginstock_subscriber_email'],
$data['cwginstock_user_id'], "en_US",$data['cwginstock_pid']
);
$tablename = $wpdb->prefix . "postmeta";
foreach ($data1 as $key => $value) {
$res = $wpdb->insert(
$tablename,
array(
'post_id' => $lastid,
'meta_key' => $value,
'meta_value' => $data3[$key]
)
);
}
if($res){
echo 'inserted';
}else{
echo 'not inserted';
}
return $wpdb;
}
}
add_action( 'rest_api_init', function () {
$namespace = 'myplugin/v1';
$endpoint = '/authorsss/';
register_rest_route( $namespace, $endpoint, array(
'methods' => 'GET',
'callback' => 'my_awesome_func'
) );
} );
i want to proper insert data in database, email alert is not coming and
in admin side in plugin product name not showing even i am sending product id
I wanted to do the same thing. I used your code as a base to start but changed some small things and it works now.
//himanshu-swamiitechs-co-in__trashed
$ok = str_replace(".","-",$data['cwginstock_subscriber_email']);
$post_name = str_replace("#","",$ok);
the str_replace needed to be different. replace . by - and remove #
$data1 = array(
'cwginstock_product_id' ,
'cwginstock_variation_id',
'cwginstock_subscriber_email',
'cwginstock_user_id',
'cwginstock_language',
'cwginstock_pid' ,
);
Secondly this is the right order and variables
Underneath you can see the whole code I used
function back_in_stock_email ( $data) {
// Get request params
global $wpdb;
if ($data['cwginstock_user_id']=='') {
$students_arr = array(
"responseCode" => 400,
"responseMessage" => "Please enter user id.",);
echo json_encode($students_arr);
} elseif ($data['cwginstock_subscriber_email'] == '') {
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter email id.",);
echo json_encode($students_arr);
} elseif($data['cwginstock_pid'] == '') {
$students_arr = array(
"responseCode" =>400,
"responseMessage" => "Please enter product id.",);
echo json_encode($students_arr);
} else {
$tablename2 = $wpdb->prefix . "posts";
//himanshu-swamiitechs-co-in__trashed
$ok = str_replace(".","-",$data['cwginstock_subscriber_email']);
$post_name = str_replace("#","",$ok);
$res = $wpdb->insert(
$tablename2,
array(
'post_author' => "0",
'post_content' => "",
'post_title' => $data['cwginstock_subscriber_email'],
'post_excerpt' => "",
'post_name'=>$post_name,
'post_status' =>'cwg_subscribed',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => "",
'to_ping' => "",
'pinged' => "",
'post_content_filtered' =>'',
'post_parent' =>'',
'guid' => '<YOUR BASE URL>/cwgstocknotifier/'.$post_name.'/',
"menu_order"=> "0",
"post_type"=> "cwginstocknotifier",
"post_mime_type" =>"",
"comment_count"=> "0",
"post_date"=>Date('Y-m-d H:i:s'),
"post_date_gmt"=>Date('Y-m-d H:i:s'),
"post_modified_gmt" =>Date('Y-m-d H:i:s'),
"post_modified"=>Date('Y-m-d H:i:s')
)
);
$lastid = $wpdb->insert_id;
echo $lastid;
$data1 = array(
'cwginstock_product_id' ,
'cwginstock_variation_id',
'cwginstock_subscriber_email',
'cwginstock_user_id',
'cwginstock_language',
'cwginstock_pid' ,
);
$data3 = array($data['cwginstock_pid'], $data['cwginstock_variation_id'],
$data['cwginstock_subscriber_email'], "0","en_US",$data['cwginstock_pid']);
$tablename = $wpdb->prefix . "postmeta";
foreach ($data1 as $key => $value) {
$res = $wpdb->insert(
$tablename,
array(
'post_id' => $lastid,
'meta_key' => $value,
'meta_value' => $data3[$key]
)
);
}
if ($res) {
echo 'inserted';
} else {
echo 'not inserted';
}
return $wpdb;
}
}

How to edit this function to improve performance in Wordpress?

I am using a wordpress/woocommerce theme named "invogue". This theme contain some ajax functions that are called using AJAX, but they are super slow >5 sec each.
Is there any way to edit this function to speed things up ?
the following gets the cart items
#GET CART NAV DATA
public function htheme_get_nav_cart_data(){
#GLOBALS
global $wpdb, $hmenu_helper, $woocommerce;
if ( class_exists( 'WooCommerce' ) ) {
#VARAIBLES
$cart_count = $woocommerce->cart->cart_contents_count;
$cart_link = esc_url(get_permalink(get_option('woocommerce_cart_page_id')));
$cart = $woocommerce->cart->get_cart();
$total_quantity = 0;
#ARRAY OF ITEMS
$cart_items = [];
$cart_count = 1;
#FOREACH CART ITEM
foreach($cart as $item){
$image = wp_get_attachment_image_src ( get_post_thumbnail_id ( $item['product_id'] ), 'full' );
$cart_items[] = array(
'id' => $item['product_id'],
'title' => esc_html($item['data']->post->post_title),
'quantity' => $item['quantity'],
'total' => $item['line_subtotal'],
'link' => get_permalink($item['product_id']),
'price' => wc_get_price_decimals(),
'image' => $image[0],
'price_html' => $this->htheme_return_price_html($item['product_id']),
'qty' => esc_html__('Qty', 'invogue'),
);
$total_quantity += $item['quantity'];
$cart_count++;
}
#ECHO JSON
echo json_encode(array(
'status' => 'active',
'count' => $total_quantity,
'url' => $cart_link,
'cart' => $cart_items,
'symbol' => get_woocommerce_currency_symbol(get_option('woocommerce_currency')),
'total' => $woocommerce->cart->get_cart_total(),
));
exit();
} else {
#NOT ACTIVE
echo json_encode(array(
'status' => 'not'
));
exit();
}
}
the following gets the wishlist items
public function htheme_get_nav_wishlist_data(){
#GLOBALS
global $wpdb, $hmenu_helper, $woocommerce;
if ( class_exists( 'WooCommerce' ) ) {
#GET USER ID
$user_ID = get_current_user_id();
#GET USER WISHLIST
$wishlist = esc_attr( get_the_author_meta( 'user_wishlist', $user_ID ) );
#ARGS
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'offset' => 0,
'include' => explode(',', $wishlist)
);
#PRODUCTS
$products = get_posts($args);
#ECHO JSON
echo json_encode($products);
exit();
} else {
#NOT ACTIVE
echo json_encode(array(
'status' => 'not'
));
exit();
}
}

Use email address as Woocommerce coupon code

I am trying to create a function to use email address as woocommerce coupon code. My code works perfect before but suddenly it stopped working. I use this woocommerce_get_shop_coupon_data filter to get the coupon data. Please help me.
<?php
add_filter ( 'woocommerce_get_shop_coupon_data', 'firefog_create_coupon', 10, 2 );
function firefog_create_coupon($data, $code) {
global $wpdb;
//getting the coupon input value
$coupon_code = $_POST['coupon_code'] ;
//check user input is like email
if (filter_var($coupon_code, FILTER_VALIDATE_EMAIL)) {
$code = $coupon_code ;
}
// Check if the coupon has already been created in the database
$sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1;", $code );
$coupon_id = $wpdb->get_var( $sql );
if ( empty( $coupon_id ) ) {
// Create a coupon with the properties you need
$data = array(
'discount_type' => 'percent',
'coupon_amount' => 15, // value
'individual_use' => 'false',
'product_ids' => array(),
'exclude_product_ids' => array(),
'usage_limit' => '',
'usage_limit_per_user' => '',//Limit
'limit_usage_to_x_items' => '',
'usage_count' => '',
'expiry_date' => '2020-12-31', // YYYY-MM-DD
'free_shipping' => 'false',
'product_categories' => array(),
'exclude_product_categories' => array(),
'exclude_sale_items' => 'false',
'minimum_amount' => '',
'maximum_amount' => '',
'customer_email' => array()
);
// Save the coupon in the database
$coupon = array(
'post_title' => $code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Write the $data values into postmeta table
foreach ($data as $key => $value) {
update_post_meta( $new_coupon_id, $key, $value );
}
return $data;
}
}

Categories