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.
Related
I'm trying to recreate a JSON file with a specific structure and only getting so far as I'm not that familiar with PHP.
I'd like to list all used/non-empty categories, then all posts within each category and then all images/other details used in each post.
I'm not sure how the code should look in the loop. I'd need the JSON to be exactly like below (brackets) as I'm feeding it to a D3 script:
{
"project": "Farm", // website name
"about": "What we have on the farm.",
"categories": [ //post categories
{
"slug": "fruits",
"title": "Fruits",
"description": "All about fruits.",
"posts": [ // all posts within a category
{
"slug": "apples",
"title": "Apples",
"excerpt": "Apple trees and fruits.",
"tags": "tree, apple",
"post_images": [
{
"id": 25,
"title": "Apple trees.",
"filename": "apple-trees.jpg",
"desc": "Rows of apple trees.",
"tags": ""
},
(...)
The PHP script so far (in functions.php):
function export_to_json() {
global $post;
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$posts = array();
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$query = new WP_Query( $post_args );
while ( $query->have_posts() ): $query->the_post();
$posts[] = array(
'categories' => [
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => [
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'images' => get_attached_media( 'image' ),
'tags' => get_tags()
]
]
);
endwhile;
wp_reset_query();
}
$data = json_encode($posts, JSON_PRETTY_PRINT);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen($save_path, "w");
fwrite($f, $data);
fclose($f);
}
add_action('save_post', 'export_to_json');
The script is wrong because categories get repeated for each post and I'd like all posts within a category to be properly nested.
Any help with this would be much appreciated. Thanks.
Here you go:
function export_to_json() {
global $post;
$categories = array();
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'category__in' => $cat->term_id
);
$get_posts = array();
$posts = get_posts( $post_args );
foreach($posts as $post){
$tags = get_the_tags($post->ID);
$i = 0;
$tag_names = '';
$post_images = array();
if( $tags) {
foreach( $tags as $tag ) { $i++;
$comma = $i == count($tags) ? '' : ', ';
$tag_names .= $tag->name . $comma;
}
}
$images = get_post_gallery($post->ID, false);
if($images){
$image_ids = explode(",", $images['ids']);
foreach ($image_ids as $image ){
$img = wp_prepare_attachment_for_js($image);
$post_images[] = array(
"id" => $img['id'],
"title" => $img['name'],
"filename" => $img['filename'],
"desc" => $img['description'], //Pulls the image description
'tags' => $tag_names
);
}
}
$get_posts[] = array(
'slug' => $post->post_name,
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'tags' => $tag_names,
'post_images' => $post_images
);
}
$categories[] = array(
'slug' => $cat->slug,
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => $get_posts
);
}
$output = array(
'project' => get_bloginfo('name'),
'about' => get_bloginfo('description'),
'categories' => $categories
);
$data = json_encode($output, JSON_PRETTY_PRINT);
}
I've created a custom rest route in Wordpress which takes a product category id and will send products which are in that category.
My Problem is I can't figure out a way to get variable product min and max prices inside my custom loop.
Can anyone help me with this issue?
Thanks
I've tried to get variation price using get_variation_prices() but it seems that I'm missing something.
add_action( 'rest_api_init' , 'wt_rest_api');
function wt_rest_api(){
register_rest_route('wtrest','products',array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'wtProductResults'
));
}
function wtProductResults($data){
$products = new WP_Query([
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id', //can be set to ID
'terms' => $data['cat'] //if field is ID you can reference by cat/term number
)
)
]);
$productsResults = [];
global $woocommerce;
global $product;
$currency = get_woocommerce_currency_symbol();
while($products->have_posts()){
$products->the_post();
$product_cat = get_term( $data['cat'], 'product_cat', 'category', "OBJECT" );
$regularPrice = get_post_meta( get_the_ID(), '_regular_price', true);
$sale = get_post_meta( get_the_ID(), '_sale_price', true);
$price = get_post_meta( get_the_ID(), '_price', true );
array_push($productsResults , [
'title' => get_the_title(),
'productId' => get_the_id(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail(),
'excerpt' => get_the_excerpt(),
'regularPrice' => $regularPrice,
'price' => $price,
'salePrice' => $sale,
'category' => $product_cat->name,
'variationPrice' => get_variation_prices()//**Here is My problem**
]);
}
wp_reset_postdata();
return $productsResults;
}
Here is my Code and when I used get_variation_prices() I didn't get any response from my rest route
The function get_variation_prices() is a method of WC_Product_Variable Class and it works exclusively as a method on a variable product instance object. It gives a multi dimensional array of all variations prices.
To get Min and Max variation prices, you have to use WC_Product_Variable methods:
get_variation_regular_price() or get_variation_regular_price('max')
get_variation_sale_price() or get_variation_sale_price('max')
get_variation_price() or get_variation_price('max')
Now in your code:
you will need first to get the WC_Product instance object.
check products type.
remove global $product; as it's empty and not useful.
(you might need to make other changes, based on your requirements)
Now there is multiple ways to query products:
1) Using a WP_Query (just as you are doing actually):
function wtProductResults($data){
global $woocommerce;
$products = new WP_Query([
'post_type' => 'product',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'term_id', //can be set to ID
'terms' => $data['cat'] //if field is ID you can reference by cat/term number
) )
]);
$productsResults = [];
$currency = get_woocommerce_currency_symbol();
if ( $products->have_posts() ) :
while ( $products->have_posts() ) : $products->the_post();
$product_cat = get_term( $data['cat'], 'product_cat', 'category', "OBJECT" );
// Get an instance of the WC_Product object
$product = wc_get_product( get_the_ID() );
if( $product->is_type('variable') ) {
// Min variation price
$regularPriceMin = $product->get_variation_regular_price(); // Min regular price
$salePriceMin = $product->get_variation_sale_price(); // Min sale price
$priceMin = $product->get_variation_price(); // Min price
// Max variation price
$regularPriceMax = $product->get_variation_regular_price('max'); // Max regular price
$salePriceMax = $product->get_variation_sale_price('max'); // Max sale price
$priceMax = $product->get_variation_price('max'); // Max price
// Multi dimensional array of all variations prices
$variationsPrices = $product->get_variation_prices();
$regularPrice = $salePrice = $price = '';
$variationPrice = [
'min' => $product->get_variation_price(),
'max' => $product->get_variation_price('max')
];
}
// Other product types
else {
$regularPrice = $product->get_regular_price();
$salePrice = $product->get_sale_price();
$price = $product->get_price();
$variationPrice = ['min' => '', 'max' => ''];
}
array_push( $productsResults , [
'title' => get_the_title(),
'productId' => get_the_id(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail(),
'excerpt' => get_the_excerpt(),
'regularPrice' => $regularPrice,
'price' => $price,
'salePrice' => $salePrice,
'category' => $product_cat->name,
'variationPrice' => $variationPrice,
]);
endwhile;
wp_reset_postdata();
endif;
return $productsResults;
}
2) Using a WC_Product_Query instead like:
function wtProductResults($data){
global $woocommerce;
$products = wc_get_products( array(
'status' => 'publish',
'limit' => -1,
'category' => array($data['cat']),
) );
$productsResults = [];
$currency = get_woocommerce_currency_symbol();
if ( sizeof($products) > 0 ) :
foreach ( $products as $product ) :
$term_name = get_term( $data['cat'], 'product_cat' )->name;
if( $product->is_type('variable') ) {
// Min variation price
$regularPriceMin = $product->get_variation_regular_price(); // Min regular price
$salePriceMin = $product->get_variation_sale_price(); // Min sale price
$priceMin = $product->get_variation_price(); // Min price
// Max variation price
$regularPriceMax = $product->get_variation_regular_price('max'); // Max regular price
$salePriceMax = $product->get_variation_sale_price('max'); // Max sale price
$priceMax = $product->get_variation_price('max'); // Max price
// Multi dimensional array of all variations prices
$variationsPrices = $product->get_variation_prices();
$regularPrice = $salePrice = $price = '';
$variationPrice = [
'min' => $product->get_variation_price(),
'max' => $product->get_variation_price('max')
];
}
// Other product types
else {
$regularPrice = $product->get_regular_price();
$salePrice = $product->get_sale_price();
$price = $product->get_price();
$variationPrice = ['min' => '', 'max' => ''];
}
array_push( $productsResults , [
'title' => $product->get_name(),
'productId' => $product->get_id(),
'permalink' => $product->get_permalink(),
'thumbnail' => $product->get_image(),
'excerpt' => $product->get_short_description(),
'regularPrice' => $regularPrice,
'price' => $price,
'salePrice' => $salePrice,
'category' => $term_name,
'variationPrice' => $variationPrice,
]);
endforeach;
endif;
return $productsResults;
}
The Answer that #LoicTheAztec gave was very good and I liked the way he write the code
but in my case I found on simple change that worked perfectly the way I want it to be both normal product price if it's normal product and variable product price if variable product
This is the change I made and I used both wc_get_product(get_the_id()) and get_price_html()
$product = wc_get_product( get_the_id() );
array_push($productsResults , [
'title' => get_the_title(),
'productId' => get_the_id(),
'permalink' => get_the_permalink(),
'thumbnail' => get_the_post_thumbnail(),
'excerpt' => get_the_excerpt(),
'category' => get_the_terms(get_the_id(),'product_cat'),
'price' => $product->get_price_html(),
]);
this code should be inside while loop that I used with WP_Query()
add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format_min', 9999, 2 );
function bbloomer_variation_price_format_min( $price, $product ) {
$prices = $product->get_variation_prices('min', true );
$maxprices = $product->get_variation_price( 'max', true ) ;
$min_price = current( $prices['price'] );
//$max_price = current( $maxprices['price'] );
$minPrice = sprintf( __( 'from: %1$s', 'woocommerce' ), wc_price( $min_price ) );
$maxPrice = sprintf( __( 'to: %1$s', 'woocommerce' ), wc_price( $maxprices ) );
return $minPrice .' ' .$maxPrice ;
}
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();
}
}
I am trying to setup a CSV feed for another marketplace.
Problem is that only one set of values are stored to the array.
$data = array();
while ($loop->have_posts()) : $loop->the_post();
$product = get_product($loop->post);
$title = $product->get_title();
$link = get_permalink();
$description = strip_tags($post->post_content);
$details = $post->the_excerpt;
$categories = get_the_terms($post->ID, 'product_cat');
$sku = $product->get_sku();
$price = $product->price;
$imageinfo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID));
$imageurl = $imageinfo[0];
$image = preg_replace($suchmuster, '', $imageurl);
foreach ($categories as $c) {
$category = $c->name;
}
$data += [
"ean" => $sku,
"condition" => "100",
"listing_price" => $price,
"minimum_price" => $price,
"amount" => 9,
"delivery_time" => "b",
"location" => "DE"
];
endwhile;
wp_reset_query();
echo '<pre>';
print_r($data);
echo '</pre>';
My Array now looks like this:
Array
(
[ean] => SportsBag16
[condition] => 100
[listing_price] => 39
[minimum_price] => 39
[amount] => 9
[delivery_time] => b
[location] => DE
)
But there should be way more entries(22).
What am i doing wrong? Thanks for any help.
You are append the output to string , you have to make the array in while conditions, in your code it replace the previous value with new values.
$data = array();
while ($loop->have_posts()) : $loop->the_post();
$product = get_product($loop->post);
$title = $product->get_title();
$link = get_permalink();
$description = strip_tags($post->post_content);
$details = $post->the_excerpt;
$categories = get_the_terms($post->ID, 'product_cat');
$sku = $product->get_sku();
$price = $product->price;
$imageinfo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID));
$imageurl = $imageinfo[0];
$image = preg_replace($suchmuster, '', $imageurl);
foreach ($categories as $c) {
$category = $c->name;
}
$array1 = array(
"ean" => $sku,
"condition" => "100",
"listing_price" => $price,
"minimum_price" => $price,
"amount" => 9,
"delivery_time" => "b",
"location" => "DE"
);
$data []= $array1;
endwhile;
wp_reset_query();
echo '<pre>';
print_r($data);
echo '</pre>';
Your error lies in using += to append to the array. Use the following instead:
$data[] = [
"ean" => $sku,
"condition" => "100",
"listing_price" => $price,
"minimum_price" => $price,
"amount" => 9,
"delivery_time" => "b",
"location" => "DE"
];
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']
);
}