Use email address as Woocommerce coupon code - php

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;
}
}

Related

Generate woocommerce coupon after gravity form submission

I want a user to enter their email in a gravity form and after submission they are emailed a unique coupon code that expires after two weeks. I have cobble together code from a few other solutions and I am successful at creating the unique code. But I can't get it to create the coupon in woocommerce.. Not being a PHP master I know I'm missing something obvious.
//* Define options/constants
define( 'ENGWP_FORM_ID', 276 ); // The ID of the form (integer)
define( 'ENGWP_SOURCE_FIELD_ID', 2 ); // The ID of the form field holding the code (integer)
define( 'ENGWP_CODE_LENGTH', 12 ); // Length of code (integer)
define( 'ENGWP_CODE_CHARS', '1234567890QWERTYUIOPASDFGHJKLZXCVBNM' ); // Available character for the code; default 0-9 and uppercase letters (string)
define( 'ENGWP_CODE_PREFIX', '17-' ); // Custom prefix for the code (string); default empty
define( 'ENGWP_DISCOUNT_TYPE', 'percent' ); // 'flat' or 'percent' (string)
define( 'ENGWP_DISCOUNT_AMOUNT', 10 ); // Value of discount (integer); $ if 'type' is 'flat' and % if 'type' is 'percent'
define( 'ENGWP_MAX_USES', 1 ); // Maximum number of uses per customer (integer)
define( 'ENGWP_MIN_PRICE', 0 ); // Minimum price for discount to apply (integer); default none
define( 'ENGWP_PRODUCT_REQS', '' ); // A comma-separated list of product IDs (string) the coupons apply to
define( 'ENGWP_REQS_CONDITION', '' ); // How to apply the discount to those products (string); accepts 'any' (at least one product ID must be in the cart) or 'all' (all products must be in the cart)
define( 'ENGWP_SINGLE_USE', 'use_once' ); // Whether the coupons generated can be used more than once by a single customer; default is set to one-time usage but can be set to false (boolean) for allowing multiple uses
define( 'ENGWP_EXCLUDE_PRODUCTS', '' ); // A comma-separated list of product IDs (string) to exclude from discount-applicability
$start_date = ''; # no date
// $start_date = '01/01/1900'; # static date
// $start_date = date( 'm/d/Y', strtotime("yesterday") );
$exp_date = date( 'm/d/Y', strtotime("+14 days") );
// $exp_date = '01/01/1900'; # static date
// $exp_date = ''; # no date
class GW_Create_Coupon {
public function __construct( $args = array() ) {
// set our default arguments, parse against the provided arguments, and store for use throughout the class
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'source_field_id' => false,
'plugin' => 'wc',
'amount' => 0,
'type' => '',
'meta' => array()
) );
// do version check in the init to make sure if GF is going to be loaded, it is already loaded
add_action( 'init', array( $this, 'init' ) );
}
public function init() {
// make sure we're running the required minimum version of Gravity Forms
if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
return;
}
add_action( 'gform_after_submission', array( $this, 'create_coupon' ), 10, 2 );
}
public function create_coupon( $entry, $form ) {
if( ! $this->is_applicable_form( $form ) ) {
return;
}
$coupon_code = rgar( $entry, $this->_args['source_field_id'] );
$amount = $this->_args['amount'];
$type = $this->_args['type'];
$plugin_func = array( $this, sprintf( 'create_coupon_%s', $this->_args['plugin'] ) );
if( is_callable( $plugin_func ) ) {
call_user_func( $plugin_func, $coupon_code, $amount, $type );
}
}
public function create_coupon_wc( $coupon_code, $amount, $type ) {
$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 );
$meta = wp_parse_args( $this->_args[‘meta’], array(
‘discount_type’ => $type,
‘coupon_amount’ => $amount,
‘individual_use’ => ‘yes’,
‘product_ids’ => ”,
‘exclude_product_ids’ => ”,
‘usage_limit’ => ‘1’,
‘expiry_date’ => ”,
‘apply_before_tax’ => ‘no’,
‘free_shipping’ => ‘no’,
‘exclude_sale_items’ => ‘no’,
‘product_categories’ => ”,
‘exclude_product_categories’ => ”,
‘minimum_amount’ => ”,
‘customer_email’ => ”
) );
foreach( $meta as $meta_key => $meta_value ) {
update_post_meta( $new_coupon_id, $meta_key, $meta_value );
}
}
public function create_coupon_edd( $coupon_code, $amount, $type ) {
if( ! is_callable( 'edd_store_discount' ) ) {
return;
}
$meta = wp_parse_args( $this->_args['meta'], array(
'name' => $coupon_code,
'code' => $coupon_code,
'type' => $type,
'amount' => $amount,
'excluded_products' => array(),
'expiration' => '',
'is_not_global' => false,
'is_single_use' => false,
'max_uses' => '',
'min_price' => '',
'product_condition' => '',
'product_reqs' => array(),
'start' => '',
'uses' => '',
) );
// EDD will set it's own defaults in the edd_store_discount() so let's filter out our own empty defaults (their just here for easier reference)
$meta = array_filter( $meta );
// EDD takes a $details array which has some different keys than the meta, let's map the keys to the expected format
$edd_post_keys = array(
'max_uses' => 'max',
'product_reqs' => 'products',
'excluded_products' => 'excluded-products',
'is_not_global' => 'not_global',
'is_single_use' => 'use_once'
);
foreach( $meta as $key => $value ) {
$mod_key = rgar( $edd_post_keys, $key );
if( $mod_key ) {
$meta[$mod_key] = $value;
}
}
edd_store_discount( $meta );
}
function is_applicable_form( $form ) {
$form_id = isset( $form['id'] ) ? $form['id'] : $form;
return $form_id == $this->_args['form_id'];
}
}
//* Instantiate the class for EDD
new GW_Create_Coupon( array(
'form_id' => ENGWP_FORM_ID,
'source_field_id' => ENGWP_SOURCE_FIELD_ID,
'amount' => ENGWP_DISCOUNT_AMOUNT,
'type' => ENGWP_DISCOUNT_TYPE,
'meta' => array(
'excluded_products' => array( ENGWP_EXCLUDE_PRODUCTS ),
'expiration' => $exp_date,
'is_not_global' => 'not_global',
'is_single_use' => ENGWP_SINGLE_USE,
'max_uses' => ENGWP_MAX_USES,
'min_price' => ENGWP_MIN_PRICE,
'product_condition' => ENGWP_REQS_CONDITION,
'product_reqs' => array( ENGWP_PRODUCT_REQS ),
'start' => $start_date,
)
) );
/**
* Generate the random codes to be used for the EDD discounts
*/
//* Generates and returns the code
add_filter( 'gform_field_value_uuid', 'gw_generate_unique_code' );
function gw_generate_unique_code() {
$length = ENGWP_CODE_LENGTH;
$chars = ENGWP_CODE_CHARS;
$prefix = ENGWP_CODE_PREFIX;
$unique = '';
$chars_length = strlen( $chars )-1;
for( $i = 0 ; $i < $length ; $i++ ) {
$unique .= $chars[ rand( 0, $chars_length ) ];
}
do {
$unique = $prefix . str_shuffle( $unique );
} while ( !gw_check_unique_code( $unique ) );
return $unique;
}
//* Checks to make sure the code generated is unique (not already in use)
function gw_check_unique_code( $unique ) {
global $wpdb;
$table = $wpdb->prefix . 'rg_lead_detail';
$form_id = ENGWP_FORM_ID; // update to the form ID your unique id field belongs to
$field_id = ENGWP_SOURCE_FIELD_ID; // update to the field ID your unique id is being prepopulated in
$result = $wpdb->get_var( "SELECT value FROM $table WHERE form_id = '$form_id' AND field_number = '$field_id' AND value = '$unique'" );
if ( empty ( $result ) ) {
return true;
} else return false;
}
You can use WC_Coupon to generate a coupon code. try the below code.
add_action( 'gform_after_submission', array( $this, 'create_coupon' ), 10, 2 );
public function create_coupon( $entry, $form ){
$coupon_code = rgar( $entry, $this->_args['source_field_id'] );
$date_expires = date('Y-m-d', strtotime('+14 days'));
$discount_type = 'fixed_cart'; // 'store_credit' doesn't exist
$coupon = new WC_Coupon();
$coupon->set_code($coupon_code);
//the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
$coupon->set_discount_type($discount_type);
//the discount amount, defaults to zero
$coupon->set_amount($amount );
$coupon->set_date_expires( $date_expires );
//save the coupon
$coupon->save();
}

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 store values (entry) from WPForm Wordpress to PhpAdmin database

Here is my problem ! I have a website with Wordpress and i'm selling items with WPForms lite editions. There is 1 form with every client's information that i need to put into my SQL database.
When a client completed a transactions successfully, WPForm as a Entry with all information i need put but i'm not able to transfer this information to my SQL database!
My Wpform information looks like this :
Invoice ID
Full name
Email
Purchase
Unit Price
Quantity
Subtotal
TPS
TVQ
Total
Billing information
Agent Number
Payment Information (stripe)
I've looked through this code......and i'm not sure what's what in this. It seems every ID of my single WPForm will be put into a value...?? but how is it suppose to go into my databse? Need explanation !
add_action( 'wpforms_process_complete', 'process_entry', 5, 4 );
function process_entry( $form_fields, $entry, $form_data, $entry_id ) {
global $wpdb;
$form_id = $form_data['id'];
$entry_data = array(
'form_id' => $form_id,
'status' => 'publish',
'referer' => $_SERVER['HTTP_REFERER'],
'date_created' => current_time( 'mysql' )
);
// Insert into wpforms_entries custom table.
$success = $wpdb->insert( $wpdb->prefix . 'wpforms_entries', $entry_data );
$entry_id = $wpdb->insert_id;
// Create meta data.
if ( $entry_id ) {
foreach ( $form_fields as $field ) {
$field = apply_filters( 'wpforms_process_entry_field', $field, $form_data, $entry_id );
if ( isset( $field['value'] ) && '' !== $field['value'] ) {
$field_value = is_array( $field['value'] ) ? serialize( $field['value'] ) : $field['value'];
$entry_metadata = array(
'entry_id' => $entry_id,
'meta_key' => $field['name'],
'meta_value' => $field_value,
);
// Insert entry meta.
$wpdb->insert( $wpdb->prefix . 'wpforms_entrymeta', $entry_metadata );
}
}
}
}
All i want is to transfer my WPForm information value to SQL database (phpadmin)
Trying this instead and.....still no getting anywhere with it. My Databse is already connected to my wordpress and yet i'm not able to anything to it.
function Formsql( $fields, $entry, $form_data, $entry_id ) {
global $wpdb;
$body = array(
'InvoiceID' => '',
'FullName' => $fields['1']['value'],
'Email' => $fields['2']['value'],
'Purchase' => $fields['3']['value'],
'UnitPrice' => $fields['4']['value'],
'Quantity' => $fields['5']['value'],
'SubTotal' => $fields['6']['value'],
'TPS' => $fields['7']['value'],
'TVQ' => $fields['8']['value'],
'Total' => $fields['9']['value'],
'BillingInfo' => $fields['10']['value'],
'AgentNumber' => $fields['11']['value'],
'Payment' => $fields['12']['value'],
);
$request = wp_remote_post($wpdb->prefix . 'Vente', array( 'body' => $body ) );
}
add_action( 'wpforms_process_complete_4427', 'Formsql', 10, 4 );

Custom post type not showing posts inserted from frontend

Hey everyone,
I have a post type called `index`, and i'm trying to build a form for users to insert posts from the frontend.
i created a page and a template for it with a form and an ajax function which insert the content to the DB using `wp_insert_post`. the function works generally, i can see the new posts added to the wp_post db in phpmyadmin. the problem is that i can't see the new posts in the admin panel. the post are counted (i can see the number goes up everytime i try the form), but not shown.
this is the functions.php ajax code (some $_get vars are to be used for meta data inserting):
add_action('wp_ajax_addtoindex', 'addtoindex');
add_action('wp_ajax_nopriv_addtoindex', 'addtoindex');
function addtoindex(){
$title = $_GET["title"];
$slug = sanitize_title_with_dashes($title,'','save');
$group = $_GET["group"];
$inst = $_GET["inst"];
$location = $_GET["location"];
$address = $_GET["address"];
$content = $_GET["content"];
$website = $_GET["website"];
$year = $_GET["year"];
$educ = $_GET["educ"];
$aud = $_GET["aud"];
$teaching = $_GET["teaching"];
$teachers = $_GET["teachers"];
$contact1 = $_GET["contact1"];
$email1 = $_GET["email1"];
$phone1 = $_GET["phone1"];
$contact2 = $_GET["contact2"];
$email2 = $_GET["email2"];
$phone2 = $_GET["phone2"];
$user = get_user_by("login",$authorid);
$authorid = $user->ID;
// Check if the group exists
$group_term = term_exists( $group, 'group', 0 );
// Create group if it doesn't exist
if ( !$group_term ) {
$group_term = wp_insert_term( $group, 'group', array( 'parent' => 0 ) );
}
// Check if the inst exists
$inst_term = term_exists( $inst, 'inst', 0 );
// Create inst if it doesn't exist
if ( !$inst_term ) {
$inst_term = wp_insert_term( $inst, 'inst', array( 'parent' => 0 ) );
}
// Check if the location exists
$location_term = term_exists( $location, 'location', 0 );
// Create location if it doesn't exist
if ( !$location_term ) {
$location_term = wp_insert_term( $location, 'location', array( 'parent' => 0 ) );
}
$custom_tax = array(
'group' => $group_term,
'inst' => $group_inst,
'location' => $group_location
);
//Post Properties
$new_post = array(
'post_title' => $title,
'post_name' => $slug,
'post_content' => $content,
'post_status' => 'pending',
'post_type' => 'index',
'post_author' => $authorid,
'comment_status' => 'closed',
'ping_status' => 'closed',
'tax_input' => $custom_tax
);
//save the new post
if ( post_type_exists( 'index' ) ) {
$pid = wp_insert_post($new_post, true);
echo 'good';
}
else{
echo "bad";
}
// Reset Post Data
wp_reset_postdata();
exit;
}
and this is the index post type code:
function post_type_index() {
register_post_type( 'index',
array(
'label' => __('Index'),
'labels' => array('name' => 'אינדקס האנתרופוסופיה','singular_name' => __('פריט לאינדקס','ohav'),'edit_item' => __('עריכת פריט אינדקס','ohav'),'add_new' => __('הוספת פריט לאינדקס','ohav'),'add_new_item' => __('הוספת פריט לאינדקס','ohav'),'all_items' => __('לכל פריטי האינדקס','ohav')),
'public' => true,
//'publicly_queryable' => true,
//'query_var' => true,
//'capability_type' => 'post',
'has_archive' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'rewrite' =>array(
'slug' => __('index','ohav'),
'with_front' => true
),
'hierarchical' => true,
'supports' => array(
'title',
'boxplace',
'editor',
'thumbnail'
)
)
);
}
add_action('init', 'post_type_index');
okay i found it!
the problem was i already had a pre_get_posts hook that changes the order of the index archive according to the post meta.
add_action( 'pre_get_posts', 'change_order_for_index' );
function change_order_for_index( $query ) {
if ( is_post_type_archive('index') ) {
$query->set( 'meta_key', '_index_featured' );
$query->set( 'orderby', 'meta_value' );
}
}
i added && !is_admin() to the if and it turned okay.
thank you Arif, your answer helped me find it.
you can add an action hook 'pre_get_posts' to include/exclude your custom post type to/from the admin post list or any for any other listing like archives.
add_filter( 'pre_get_posts', 'include_custom_type_index' );
function include_custom_type_index( $query ) {
$query->set( 'post_type', array(
'post', 'index'
));
return $query;
}

Create an order programmatically with line items in Woocommerce 3+

I needed to create a Woocommerce order programatically, however using the 'old' Woocommerce made this a very dirty procedure.
I had to insert all kind of database records manually, using many update_post_meta calls.
Looking for a better solution.
With latest version of WooCommerce is possible try this as something like
$address = array(
'first_name' => 'Fresher',
'last_name' => 'StAcK OvErFloW',
'company' => 'stackoverflow',
'email' => 'test#test.com',
'phone' => '777-777-777-777',
'address_1' => '31 Main Street',
'address_2' => '',
'city' => 'Chennai',
'state' => 'TN',
'postcode' => '12345',
'country' => 'IN'
);
$order = wc_create_order();
$order->add_product( get_product( '12' ), 2 ); //(get_product with id and next is for quantity)
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->add_coupon('Fresher','10','2'); // accepted param $couponcode, $couponamount,$coupon_tax
$order->calculate_totals();
Call this above code with your function then it will work accordingly.
Note it not work with old version of WooCommerce like 2.1.12, It works only from 2.2 of WooCommerce.
Hope it helps
2017-2021 For WooCommerce 3 and Above
Woocommerce 3 has introduced CRUD objects and there is lot of changes on Order items… Also some WC_Order methods are now deprecated like add_coupon().
Here is a function that allow creating programmatically an order nicely with all required data in it, including the taxes:
function create_wc_order( $data ){
$gateways = WC()->payment_gateways->get_available_payment_gateways();
$order = new WC_Order();
// Set Billing and Shipping adresses
foreach( array('billing_', 'shipping_') as $type ) {
foreach ( $data['address'] as $key => $value ) {
if( $type === 'shipping_' && in_array( $key, array( 'email', 'phone' ) ) )
continue;
$type_key = $type.$key;
if ( is_callable( array( $order, "set_{$type_key}" ) ) ) {
$order->{"set_{$type_key}"}( $value );
}
}
}
// Set other details
$order->set_created_via( 'programatically' );
$order->set_customer_id( $data['user_id'] );
$order->set_currency( get_woocommerce_currency() );
$order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
$order->set_customer_note( isset( $data['order_comments'] ) ? $data['order_comments'] : '' );
$order->set_payment_method( isset( $gateways[ $data['payment_method'] ] ) ? $gateways[ $data['payment_method'] ] : $data['payment_method'] );
$calculate_taxes_for = array(
'country' => $data['address']['country'],
'state' => $data['address']['state'],
'postcode' => $data['address']['postcode'],
'city' => $data['address']['city']
);
// Line items
foreach( $data['line_items'] as $line_item ) {
$args = $line_item['args'];
$product = wc_get_product( isset($args['variation_id']) && $args['variation_id'] > 0 ? $$args['variation_id'] : $args['product_id'] );
$item_id = $order->add_product( $product, $line_item['quantity'], $line_item['args'] );
$item = $order->get_item( $item_id, false );
$item->calculate_taxes($calculate_taxes_for);
$item->save();
}
// Coupon items
if( isset($data['coupon_items'])){
foreach( $data['coupon_items'] as $coupon_item ) {
$order->apply_coupon(sanitize_title($coupon_item['code']));
}
}
// Fee items
if( isset($data['fee_items'])){
foreach( $data['fee_items'] as $fee_item ) {
$item = new WC_Order_Item_Fee();
$item->set_name( $fee_item['name'] );
$item->set_total( $fee_item['total'] );
$tax_class = isset($fee_item['tax_class']) && $fee_item['tax_class'] != 0 ? $fee_item['tax_class'] : 0;
$item->set_tax_class( $tax_class ); // O if not taxable
$item->calculate_taxes($calculate_taxes_for);
$item->save();
$order->add_item( $item );
}
}
// Set calculated totals
$order->calculate_totals();
if( isset($data['order_status']) ) {
// Update order status from pending to your defined status and save data
$order->update_status($data['order_status']['status'], $data['order_status']['note']);
$order_id = $order->get_id();
} else {
// Save order to database (returns the order ID)
$order_id = $order->save();
}
// Returns the order ID
return $order_id;
}
Code goes in function.php file of your active child theme (or active theme) or in a plugin file.
USAGE EXAMPLE from a data array:
create_wc_order( array(
'address' => array(
'first_name' => 'Fresher',
'last_name' => 'StAcK OvErFloW',
'company' => 'stackoverflow',
'email' => 'test1#testoo.com',
'phone' => '777-777-777-777',
'address_1' => '31 Main Street',
'address_2' => '',
'city' => 'Chennai',
'state' => 'TN',
'postcode' => '12345',
'country' => 'IN',
),
'user_id' => '',
'order_comments' => '',
'payment_method' => 'bacs',
'order_status' => array(
'status' => 'on-hold',
'note' => '',
),
'line_items' => array(
array(
'quantity' => 1,
'args' => array(
'product_id' => 37,
'variation_id' => '',
'variation' => array(),
)
),
),
'coupon_items' => array(
array(
'code' => 'summer',
),
),
'fee_items' => array(
array(
'name' => 'Delivery',
'total' => 5,
'tax_class' => 0, // Not taxable
),
),
) );
With the new release of WC 2, it's much better.
However:
I do not want to use the REST API, cause I am doing a call from my own WP plugin directly. I see no use in doing a curl to my localhost
The 'WooCommerce REST API Client Library' is not useful for me cause it relay's on the REST API and it doesn't support a Create Order call
To be honest, WooCom's API Docs are limited, maybe they are still in the progress of updating it. They currently don't tell me how to create a new order, which params are required etc.
Any way, I figured out how to create an order with a line order (your product) using the classes and functions used by the REST API and I want to share it!
I created my own PHP class:
class WP_MyPlugin_woocommerce
{
public static function init()
{
// required classes to create an order
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-exception.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-server.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-resource.php';
require_once WOOCOMMERCE_API_DIR . 'interface-wc-api-handler.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-json-handler.php';
require_once WOOCOMMERCE_API_DIR . 'class-wc-api-orders.php';
}
public static function create_order()
{
global $wp;
// create order
$server = new WC_API_Server( $wp->query_vars['wc-api-route'] );
$order = new WC_API_Orders( $server );
$order_id = $order->create_order( array
(
'order' => array
(
'status' => 'processing'
, 'customer_id' => get_current_user_id()
// , 'order_meta' => array
// (
// 'some order meta' => 'a value
// , some more order meta' => 1
// )
, 'shipping_address' => array
(
'first_name' => $firstname
, 'last_name' => $lastname
, 'address_1' => $address
, 'address_2' => $address2
, 'city' => $city
, 'postcode' => $postcode
, 'state' => $state
, 'country' => $country
)
, 'billing_address' => array(..can be same as shipping )
, 'line_items' => array
(
array
(
'product_id' => 258
, 'quantity' => 1
)
)
)
) );
var_dump($order_id);
die();
}
}
Important:
The 'WOOCOMMERCE_API_DIR' constant points to '/woocommerce/includes/api/' in your plugin dir.
The order is assigned to a customer, in my case the current logged in user. Make sure your user has a role that has the capability to read, edit, create and delete orders. My role looks like this:
$result = add_role(
'customer'
, __( 'Customer' )
, array
(
'read' => true
// , 'read_private_posts' => true
// , 'read_private_products' => true
, 'read_private_shop_orders' => true
, 'edit_private_shop_orders' => true
, 'delete_private_shop_orders' => true
, 'publish_shop_orders' => true
// , 'read_private_shop_coupons' => true
, 'edit_posts' => false
, 'delete_posts' => false
, 'show_admin_bar_front' => false
)
);
If you want to look at the shop manager's rights, check
var_dump(get_option( 'wp_user_roles'));
My create_order function nicely creates an order, with the lineitem in the order_items tables.
Hope I helped you out, it took me a while to get it right.
A lot of answers do you show the best filter(hook) to use. I searched for days because when I used the 'init' it kept making more orders. In 2 mins I had 30 orders. Anyway use this code and 1 order will be created. Also, change $product = wc_get_product( '1001' ) to your product id.Reference is here on line 144: https://github.com/dipolukarov/wordpress/blob/master/wp-content/plugins/woocommerce/classes/class-wc-checkout.php
function my_init2() {
$order = wc_create_order();
$order_id = $order->get_id();
$product = wc_get_product( '10001' );
$address = array(
'first_name' => 'John2',
'last_name' => 'Smith1',
'email' => 'johnsmith1#gmail.com',
);
//$order->date_created(2020-07-21 );
$order->add_product( $product, 1 );
$order->set_address( $address, 'billing' );
$order->set_created_via( 'programatically' );
$order->calculate_totals();
$order->set_total( $product->get_price() );
$order->update_status( 'wc-completed' );
error_log( '$order_id: ' . $order_id );
}
//add_action('admin_init','my_init2');
function my_run_only_once() {
if ( get_option( 'my_run_only_once_20' ) != 'completed' ) {
my_init2();
update_option( 'my_run_only_once_20', 'completed' );
}
}
add_action( 'admin_init', 'my_run_only_once' );

Categories