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;
}
}
Related
I try to implement the Rawg.io API to my Wordpress Functions.php File but it doesn't work, i tried my code with another API and it is working fine, i think it has something to do with the API link Page='.$current_page.'
as you can see i created an custom post type to add the games to.
i also created custom fields with the right field keys.
My Report.txt file keeps returning current page = 1
function register_game_cpt() {
register_post_type( 'game', array(
'label' => 'Games',
'public' => true,
'capability_type' => 'post',
'supports' => array('title', 'editor', 'thumbnail'),
'taxonomies' => array('recordings', 'category', 'whatever', 'post_tag'),
));
}
add_action( 'init', 'register_game_cpt' );
// if ( ! wp_next_scheduled( 'update_game_list' ) ) {
// wp_schedule_event( time(), 'weekly', 'update_game_list' );
// }
add_action( 'update_game_list', 'get_games_from_api' );
add_action( 'wp_ajax_nopriv_get_games_from_api', 'get_games_from_api' );
add_action( 'wp_ajax_get_games_from_api', 'get_games_from_api' );
function get_games_from_api() {
$file = get_stylesheet_directory() . '/report.txt';
$current_page = ( ! empty( $_POST['current_page'] ) ) ? $_POST['current_page'] : 1;
$games = [];
// Should return an array of objects
$results = wp_remote_retrieve_body(wp_remote_get('https://api.rawg.io/api/games?key=/////////////////////&page='.$current_page.'&page_size=40'));
file_put_contents($file, "Current Page: " . $current_page. "\n\n", FILE_APPEND);
// turn it into a PHP array from JSON string
$results = json_decode( $results );
// Either the API is down or something else spooky happened. Just be done.
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
$games[] = $results;
foreach( $games[0] as $game ){
$game_slug = sanitize_title( $game->name . '-' . $game->id );
$existing_game = get_page_by_path( $game_slug, 'OBJECT', 'game' );
if( $existing_game === null ){
$inserted_game = wp_insert_post( [
'post_name' => $game_slug,
'post_title' => $game_slug,
'post_type' => 'game',
'post_status' => 'publish'
] );
if( is_wp_error( $inserted_game ) || $inserted_game === 0 ) {
die('Could not insert game: ' . $game_slug);
error_log( 'Could not insert game: ' . $game_slug );
continue;
}
// add meta fields
$fillable = [
'field_62684fc72d524' => 'count',
'field_6266cb41982d3' => 'name',
'field_6266cb4c982d4' => 'publishers',
'field_6266cb54982d5' => 'genres',
'field_6266cb64012e9' => 'platforms',
'field_6266cb722ebe8' => 'dates',
'field_626850012d525' => 'results',
];
foreach( $fillable as $key => $name ) {
update_field( $key, $game->$name, $inserted_game );
}
} else {
$existing_game_id = $existing_game->ID;
$exisiting_game_timestamp = get_field('updated_at', $existing_game_id);
if( $game->updated_at >= $exisiting_game_timestamp ){
$fillable = [
'field_62684fc72d524' => 'count',
'field_6266cb41982d3' => 'name',
'field_6266cb4c982d4' => 'publishers',
'field_6266cb54982d5' => 'genres',
'field_6266cb64012e9' => 'platforms',
'field_6266cb722ebe8' => 'dates',
'field_626850012d525' => 'results',
];
foreach( $fillable as $key => $name ){
update_field( $name, $game->$name, $existing_game_id);
}
}
}
}
$current_page = $current_page + 1;
wp_remote_post( admin_url('admin-ajax.php?action=get_games_from_api'), [
'blocking' => false,
'sslverify' => false, // we are sending this to ourselves, so trust it.
'body' => [
'current_page' => $current_page
]
] );
}
I am making a plugin to display all user info in a DataTables but i am failed to implement Search, filter and Pagination . I have about 20k users. Please help me.
may be I need to change my query to join wp_users and wp_usermeta and get the result for my case. I have fount a question here and a similar tutorial here . I am not good in writing MySQL query. Please help me with this.
I get ajax response like
{
"draw": 1,
"recordsTotal": 1,
"recordsFiltered": 1,
"data": [
[
"example#mail.com",
"Some Name",
"",
"admin",
""
]
]
}
This is my table structure
<table id="user_table" class="display table table-striped table-bordered dataTable" style="width:100%">
<thead class="user-table">
<tr>
<th>Email</th>
<th>Name </th>
<th>Url</th>
<th>nickname</th>
<th>description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My script
jQuery(document).ready(function($){
$(window).on('load', function () {
setTimeout(loadtable, 200);
});
function loadtable(){
var ajaxurl = USERAjax.wpajaxusersearch;
var dataTable = $('#user_table').DataTable({
"processing":true,
"serverSide": true,
"order":[],
"pageLength": 10,
"ajax":{
url: ajaxurl,
type:"POST"
},
});
}
});
also added localize script like
function users_assets_scripts(){
wp_register_script( 'jquery_datatables_js', plugins_url( 'asset/js/datatables.min.js' , __FILE__ ), array(),null,true );
wp_enqueue_script( 'jquery_datatables_js' );
wp_register_style( 'jquery_datatables_css', plugins_url( 'asset/css/datatables.min.css' , __FILE__ ));
wp_enqueue_style( 'jquery_datatables_css' );
wp_localize_script( 'jquery', 'USERAjax', array('wpajaxusersearch' => admin_url( 'admin-ajax.php?action=wpajaxusersearch' )) );
}
add_action('wp_enqueue_scripts', 'users_assets_scripts');
and my data fetching function with ajax response
<?php
function wpajaxusersearch(){
$request=$_REQUEST;
global $wpdb;
$sort= "user_registered";
//Build the custom database query to fetch all user IDs
$all_users_id = $wpdb->get_results("SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY $sort ASC LIMIT ".$request['start'].",".$request['length']." " );
$totalData=$wpdb->num_rows;
$data=array();
foreach ( $all_users_id as $i_users_id ) {
$user = get_userdata( $i_users_id->ID);
$email =$user->user_email;
$user_fullname =$user->first_name . ' ' . $user->last_name;
$user_url =$user->user_url;
$user_nickname =$user->nickname;
$user_profile =$user->description;
$sub_array = array();
$sub_array[] = $email;
$sub_array[] = $user_fullname;
$sub_array[] = $user_url;
$sub_array[] = $user_nickname;
$sub_array[] = $user_profile;
$data[] = $sub_array;
}
$json_data=array(
"draw" => (isset($request["draw"]) ? $request["draw"] : 0),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalData),
"data" => $data
);
echo json_encode($json_data);
wp_die(); //to remove that 0 response
}
add_action( 'wp_ajax_wpajaxusersearch', 'wpajaxusersearch' );
add_action( 'wp_ajax_nopriv_wpajaxusersearch', 'wpajaxusersearch' );
Add these to your theme's 'functions.php' and everything should be fine.
// change user query to treat meta result as OR part
add_action( 'pre_user_query', 'user_meta_OR_search');
function user_meta_OR_search($q){
if ($search = $q->get('_meta_or_search')){
add_filter( 'get_meta_sql', function( $sql ) use ( $search ){
global $wpdb;
// run once
static $nr = 0;
if( 0 != $nr++ ) return $sql;
// modify WHERE
$where = sprintf(
" AND ( %s OR %s OR %s ) ",
$wpdb->prepare( "{$wpdb->users}.user_email like '%%%s%%'", $search),
$wpdb->prepare( "{$wpdb->users}.user_url like '%%%s%%'", $search),
mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
);
$sql['where'] = $where;
return $sql;
});
}
}
function wpajaxusersearch()
{
$request = $_REQUEST;
$columns = array('user_email','first_name','user_url','nickname','description');
$search = esc_attr( trim( $request['search']['value'] ) );
$args = array();
$limit_args = array( 'number' => $request['length'], 'offset' => $request['start'] );
$order_args = array();
$search_args = array();
if ( isset($request['order']) && count($request['order']) )
{
$sort_column = $request['order'][0]['column'];
$sort_column_name = $columns[$sort_column];
$sort_dir = $request['order'][0]['dir'];
if( stristr( $sort_column_name,'user_' ))
$order_args = array( 'orderby' => $sort_column_name, 'order' => $sort_dir );
else
$order_args = array( 'meta_key' => $sort_column_name, 'orderby' => 'meta_value', 'order' => $sort_dir );
}
else
$order_args = array( 'orderby' => 'user_registered', 'order' => 'ASC' );
$args = $order_args;
if(isset($search) && $search != "")
{
$search_args = array(
'_meta_or_search' => "*{$search}*",
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => $search,
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $search,
'compare' => 'LIKE'
),
array(
'key' => 'nickname',
'value' => $search,
'compare' => 'LIKE'
),
array(
'key' => 'description',
'value' => $search,
'compare' => 'LIKE'
)
)
);
}
$all_users = new WP_User_Query( $args );
$total_users = count($all_users->get_results());
$filtered_users = count($all_users->get_results());
if(isset($search) && $search != "")
{
$args = array_merge($args, $search_args);
$all_users = new WP_User_Query( $args );
$filtered_users = count($all_users->get_results());
}
$args = array_merge($args, $limit_args);
$all_users = new WP_User_Query( $args );
foreach ( $all_users->get_results() as $user ) {
$email = $user->user_email;
$user_fullname = $user->first_name . ' ' . $user->last_name;
$user_url = $user->user_url;
$user_nickname = $user->nickname;
$user_profile = $user->description;
$sub_data = array();
$sub_data[] = $email;
$sub_data[] = $user_fullname;
$sub_data[] = $user_url;
$sub_data[] = $user_nickname;
$sub_data[] = $user_profile;
$data[] = $sub_data;
}
$json_data=array(
"draw" => (isset($request["draw"]) ? $request["draw"] : 0),
"recordsTotal" => intval($total_users),
"recordsFiltered" => intval($filtered_users),
"data" => $data
);
echo json_encode($json_data);
wp_die();
}
add_action( 'wp_ajax_wpajaxusersearch', 'wpajaxusersearch' );
add_action( 'wp_ajax_nopriv_wpajaxusersearch', 'wpajaxusersearch' );
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;
}
}
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']
);
}
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;
}