I am using the following API code to send an SMS when a new order is placed, the SMS API code is working to send SMS... Placed at the end of child theme in functions.php file... all is updated(WordPress 5.9.3 and woo-commerce 6.4 with PHP 8.0)
2 Issues:
The $order_id and $order_date do not populate in the given variables and the SMS is received as is with the 2 variables.
When the order is placed by a customer this code is triggered and SMS is received even when the payment is not made and the order status in the backend is showing pending payment.
Tried the following:
For the 1st issue I changed the message variable to '$order_id' or '.$order_id.' but it did not work and wp crashed so had to keep plain $order_id...
For the 2nd issue, I changed the hook to 'woocommerce_order_status_processing' but this code does not work for a new order.
Documentation: https://www.textlocal.in/free-developer-sms-api/
Any suggestions to tweak the code so both the problems are solved?
Thanks
// Sending SMS to customers on new orders
add_action('woocommerce_new_order', 'custom_msg_customer_process_order', 10, 3);
function custom_msg_customer_process_order ($order_id) {
$order = new WC_Order( $order_id );
$order_date = $order->get_date_created();
$billing_phone = $order->get_billing_phone();
$apiKey = urlencode('apikey');
// Message details
$numbers = array($billing_phone,91xxxxxxxxxx);
$sender = urlencode('TXTCL');
$message = rawurlencode('Thank you for buying from us, a Wellness product. Your order number $order_id Dated $order_date is confirmed.');
$numbers = implode(',', $numbers);
// Prepare data for POST request
$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
// Send the POST request with cURL
$ch = curl_init('https://api.textlocal.in/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
echo $response;
}
While I don't know much about the texting API (and I sure hope your customers are opting in to text updates!), what I think is happening is that new WC_Order never reads your data from the database. How you should get a new order object is wc_get_order(). However, the woocommerce_new_order hook passes along the $order object as the 2nd parameter
So if we make sure our callback is expecting a second parameter there's no need to re-instantiate the order object.
As for part 2, woocommerce_new_order will fire when the order is saved to the DB and it doesn't matter what the order status is. Instead, I think we can use woocommerce_order_status_pending_to_processing which is what the new order email uses.
/**
* Sending SMS to customers on new orders.
*
* #param int $order_id The order ID. *
* #param WC_Order $order Order object.
*/
function custom_msg_customer_process_order( $order_id, $order ) {
$order_date = $order->get_date_created();
$billing_phone = $order->get_billing_phone();
$apiKey = urlencode('apikey');
// Message details
$numbers = array($billing_phone,91xxxxxxxxxx);
$sender = urlencode('TXTCL');
// Use sprintf() to replace placeholders with values.
$message = rawurlencode( sprintf( 'Thank you for buying from us, a Wellness product. Your order number %s Dated %s is confirmed.', $order_id, $order_date ) );
$numbers = implode(',', $numbers);
// Prepare data for POST request
$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
// Send the POST request with cURL
$ch = curl_init('https://api.textlocal.in/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
echo $response;
}
add_action('woocommerce_order_status_pending_to_processing', 'custom_msg_customer_process_order', 10, 2 );
Alternative
The above depends on your gateway setting the order to processing. If it does not (or if it wasn't initially pending) then it may not fire... since it only fires on the transition from pending to processing. A better hook might actually be woocommerce_payment_complete. But note that in source, it only passes 1 parameter to its callbacks... the $order_id (similar to the woocommerce_thankyou hook does). Therefore the code snippet would need to be adjusted to expect only a single parameter:
/**
* Sending SMS to customers on new orders.
*
* #param int $order_id The order ID. *
*/
function custom_msg_customer_process_order( $order_id ) {
$order = wc_get_order( $order_id );
// Quit early if not a valid order.
if ( ! $order ) {
return;
}
$order_date = wc_format_datetime( $order->get_date_created() );
$billing_phone = $order->get_billing_phone();
$apiKey = urlencode('apikey');
// Message details
$numbers = array($billing_phone,91xxxxxxxxxx);
$sender = urlencode('TXTCL');
// Use sprintf() to replace placeholders with values.
$message = rawurlencode( sprintf( 'Thank you for buying from us, a Wellness product. Your order number %s Dated %s is confirmed.', $order_id, $order_date ) ) );
$numbers = implode(',', $numbers);
// Prepare data for POST request
$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
// Send the POST request with cURL
$ch = curl_init('https://api.textlocal.in/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
echo $response;
}
add_action('woocommerce_payment_complete', 'custom_msg_customer_process_order' );
Related
I have this code below, it works perfectly, but I can use a proxy to change all the data (I also can change the receiver email) :/
How can I make it a POST checkout method? Now it's a GET method
<?php
public function checkout()
{
$query = [];
$query['cmd'] = '_cart';
$query['upload'] = 1;
$query['business'] = $this->getCredential();
foreach ($this->getItems() as $id => $item)
{
$id = $id + 1;
$query['item_name_' . $id] = $item['name'];
$query['amount_' . $id] = $item['amount'];
$query['quantity_' . $id] = $item['quantity'];
}
$query['custom'] = $this->getReference();
$query['<first_name>'] = $this->first_name;
$query['<last_name>'] = $this->last_name;
$query['<email>'] = $this->customer_email;
$query['notify_url'] = $this->getNotificationURL();
$query['return'] = $this->getReturnURL();
$query['cancel_return'] = $this->getCancelURL();
$query['rm'] = '2';
$query['cbt'] = 'Retornar para o site';
$query['lc'] = $this->getLocation();
$query['currency_code'] = $this->getCurrency();
$query_string = http_build_query($query);
return "https://". ($this->isSandbox() ? 'sandbox' : 'www' ) .".paypal.com/cgi-bin/webscr?".$query_string;
}
I also tried the code below, but when I click to finish the payment, it return me to the return URL with the token and payer_id, but don't pay :C
public function checkout()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api-m.paypal.com/v2/checkout/orders');
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: ' . $this->getAccessToken(),
'Prefer: return=representation'
]);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode([
'brand_name' => 'yStore Plugins',
'intent' => 'CAPTURE',
'purchase_units' => $this->getItems(),
'application_context' => [
'notify_url' => $this->getNotificationURL(),
'cancel_url' => $this->getCancelURL(),
'return_url' => $this->getReturnURL()
]
]));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($curl));
curl_close($curl);
return $response->links[1]->href;
}
Follow the Set up standard payments guide which in its 'Add and modify the code' section explains that you should make 2 routes on your server, one for 'Create Order' and one for 'Capture Order', documented here. For PHP you can use the Checkout-PHP-SDK (not any older or deprecated SDK). When accessed by a browser, both routes you create should only output JSON data (no additional HTML or text which cannot be parsed as JSON). Inside the 2nd route, when the capture API is successful you should store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as sending confirmation emails or reserving product) immediately before forwarding your return JSON to the frontend caller.
Pair those 2 routes with the frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server , which has important client-side error handling.
So I have been working on a project to integrate custom SMS API with woocommerce and wc vendor plugins. Unfortunately, I didn't find any particular solution for this. Everyone was talking about some plugins who actually support existing gateways. I was wondering what if someone wants to integrate own api with woocommerce!
Finally, I have come up with own code which is given below. The code goes to function.php in your child theme. FYKI, I had to use rawurlencode to encode the text message as some telcos require encoded message.
Thank you.
Special thanks to: Integrating SMS api with woocommerce , Not sending messages
//DYNAMIC ORDER MSG TO CUSTOMER
add_action('woocommerce_order_status_processing', 'custom_msg_customer_process_order', 10, 3);
function custom_msg_customer_process_order ($order_id) {
//Lets get data about the order made
$order = new WC_Order($order_id);
//Now will fetch billing phone
$billing_phone = $order->get_billing_phone();
$billing_name = $order->get_billing_first_name();
$textmessage = rawurlencode("Dear $billing_name, Thank you for your order. Your order #$order_id is being processed. Please wait for confirmation call.");
// Now put HTTP SMS API URL
$url = "http://msms.THE_COMPANY.com/RequestSMS.php?user_name=YOUR_USER_NAME&pass_word=YOUR_PASSWORD&brand=YOUR_BRAND_NAME&type=1&destination=$billing_phone&sms=$textmessage";
// NOW WILL CALL FUNCTION CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $order_id;
}
I recently had this challenge myself, I had found an easy way to send notification SMS messages from WooCommerce with a plugin but I needed something to send messages in my own way.
I ended up using the Twilio service along with their API, I wrote up this tutorial as to how you can get it all set up so hope it helps!
function wpcodetips_send_sms( $smsMessage , $contactNumber ){
// Change to your account SID
$accountSID = 'XXXXXXXXXXXXX';
// Change to your account Auth Key
$authKey = 'XXXXXXXXXXXXX';
// Change to your account trial number
$sendNumber = '+XXXXXXXXXXX';
// The Twilio API Url
$url = "https://api.twilio.com/2010-04-01/Accounts/".$accountSID."/Messages.json";
// The data being sent to the API
$data = array(
'From' => $sendNumber,
'To' => $contactNumber,
'Body' => $smsMessage
);
// Set the authorisation header
$headers = array( 'Authorization' => 'Basic ' . base64_encode($accountSID . ':' . $authKey));
// Send the POST request and store the response in a variable
$result = wp_remote_post($url, array( 'body' => $data, 'headers' => $headers));
// Return the response body to ensure it has worked
return json_decode($result['body'], true);
}
https://www.wpcodetips.com/wordpress-tutorials/how-to-send-an-sms-from-wordpress-programmatically/
Not sure if this helps anyone but I recently set up a woocommerce shop where the owners are not able to check their email for orders all day as they are out on the field.
So with the mix of Hasan's and Gary's post right here I consolidated them into one to make a notification over SMS using Twilio when a new order comes in.
Just add the below to your functions.php and replace the accountSID, authKey, SendNumber and contactNumber values. And of course change the message to your preference.
Tested it with special characters like ÅÄÖ as well and it worked.
//Send SMS Notification to admin
add_action('woocommerce_order_status_processing', 'send_woo_order_sms', 10, 3);
function send_woo_order_sms ($order_id){
//Get order data
$order = new WC_Order($order_id);
//Get first name from order
$billing_first_name = $order->get_billing_first_name();
//Get last name from order
$billing_last_name = $order->get_billing_last_name();
// Change to your Twilio account SID
$accountSID = 'xxxxxxxxxxxxxxxx';
// Change to your Twilio account Auth Key
$authKey = 'xxxxxxxxxxxxxxxx';
// Change to your Twilio account number
$sendNumber = '+xxxxxxxxxxxxxxxx';
//Change to your verified caller number (receiver of the sms)
$contactNumber = '+xxxxxxxxxxxxxxxx';
//Message to send
$smsMessage = "$billing_first_name $billing_last_name has just placed an order. See order #$order_id.";
// The Twilio API Url
$url = "https://api.twilio.com/2010-04-01/Accounts/".$accountSID."/Messages.json";
// The data being sent to the API
$data = array(
'From' => $sendNumber,
'To' => $contactNumber,
'Body' => $smsMessage
);
// Set the authorisation header
$headers = array( 'Authorization' => 'Basic ' . base64_encode($accountSID . ':' . $authKey));
// Send the POST request and store the response in a variable
$result = wp_remote_post($url, array( 'body' => $data, 'headers' => $headers));
return $order_id;
}
I guess it could easily be changed to be sent out to the customer instead by changing the contactNumber to the billing phone.
$contactNumber = $order->get_billing_phone();
This would however require a paid plan at Twilio.
Ufone pakistan sms integration with woocommerce wordpress
if you are looking for integration with ufone pakistan sms api bsms ufone pakistan service provider with woocommerce wordpress then use the following code in your functions file
sms api integration ufone bsms with wordpress woocommerce
thanks to the author on this page
Integrating custom SMS API with woocommerce
//add this line for calling your function on creation of order in woocommerce
add_action('woocommerce_order_status_processing', 'custom_func', 10, 3);
function custom_func ($order_id) {
$order_details = new WC_Order($order_id);
//fetch all required fields
$billing_phone = $order_details->get_billing_phone();
$billing_name = $order_details->get_billing_first_name();
$billing_last_name = $order_details->get_billing_last_name();
$total_bill = $order_details->get_total();
$textmessage = rawurlencode("Dear $billing_name, Thank you for your order. Your order #$order_id is being processed. Please wait for confirmation call Total Bill = $total_bill");
// Now put HTTP ufone BSMS API URL
$url = "https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=msisdn&message=$textmessage&shortcode=SHORTCODE&lang=English&mobilenum=$billing_phone&password=password&messagetype=Nontransactional";
// NOW WILL CALL FUNCTION CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $order_id;
}
Iv'e written a method to subscribe users to MailChimp. Whats 'special' about it is that it automatically subscribe the users to groups within the list, and segments within the list, based on the users' cart items, wishlist items, and the item and / or category that he has subscribed from.
The integration with MailChimp is straight forward - I get the data > send curl > get response > handle response.
I'm looking for a way to constant update the users' groups and segments, based on their actions in my store.
Now, the only accepted statuses MailChimp can get are 'subscribed', 'pending', and 'clean'. All of them aren't updating, only inserting new subscribers. If the email is already subscribed, nothing is being updated, not even data that is different than what the subscriber has in its profile in my MailChimp lists.
Here's my code for reference:
protected static function subscribeToMailchimp($email, $fullname)
{
$params = EkerbaseJoomla::getPluginParams('system', 'ekerbaseusers');
$interests = self::getUserInterestsObject();
$apikey = $params->mailChimpApiKey;
$listId = $params->mailChimpListId;
$interestCategoryId = $params->mailChimpInterestCategoryId;
$auth = base64_encode( 'user:' . $apikey );
$apiUrl = 'https://'.substr($params->mailChimpApiKey, -3).'.api.mailchimp.com/3.0/lists/'.$listId;
$possibleGroups = json_decode(file_get_contents($apiUrl . '/interest-categories/' . $interestCategoryId . '/interests?apikey=' . $apikey))->interests;
$segments = json_decode(file_get_contents($apiUrl . '/segments?apikey=' . $apikey))->segments;
$data = [
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' =>
[
'FNAME' => $fullname
]
];
if( ! empty($interests->categories) ) {
$data['interests'] = [];
foreach( $possibleGroups as $group ) {
if( in_array($group->name, $interests->categories) ) {
$data['interests'][$group->id] = true;
}
}
}
if( ! empty($interests->items) ) {
$data['segments'] = [];
foreach( $segments as $segment ) {
if( in_array($segment->name, $interests->items) ) {
$data['segments'][$segment->id] = true;
}
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/members/');
curl_setopt($ch, CURLOPT_HTTPHEADER,
[
'Content-Type: application/json',
'Authorization: Basic '.$auth
]
);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
$response = json_decode($result);
switch( $response->status ) {
case 'subscribed':
$responseMessage = JText::_('EKERBASE_SUCCESS_NEWSLETTER');
$responseStatus = 'success';
$responseResult = 'mailchimp subscribing succeeded';
break;
default:
$responseStatus = 'error';
$responseMessage = $response->title;
$responseResult = 'mailchimp subscribing failed';
if( $response->title === 'Member Exists' ) {
$responseMessage = JText::_('EKERBASE_NEWSLETTER_ALREADY_SUBSCRIBER');
}
break;
}
return EkerbaseAjax::buildJsonResponse($responseMessage, $responseStatus, $responseResult);
}
If your integration is adding entirely new subscriber as expected, and the issue appears isolated to cases where the method is updating an existing sub's record, the issue may pertain to the HTTP method, and/or the api endpoint.
As v3 of MailChimp's API only allows subscribers to be initialized when using the POST method(which looks like it may be hard coded into cURL here), and is likely why entirely new subscribers are being added without issue.
This said, when wanting to add or update new subscribers using PUT would be recommended, and is specified in their docs.
Add or update a list member
more on http methods and their API
Additionally, along with this alternate method usage, to ensure existing subscribers are updated, you'll also need to append the MD5 hash of the lower case version of their email to to the endpoint. This only needs to be done for existing subs.
e.g. /members/{lowercase_email_MD5_hash}
Which should be provided in the response if you're first checking with MailChimp whether or not a subscriber exist, if you'd like to recycle that.
Hello Stackoverflow :)
I'm building a script for a client that has an e-paper that comes out everyday.
The e-paper is build by a 3rd party and when they publish it, they can have their system visit an URL of our choice.
When their system visits our URL we wan't a mailchimp automated e-mail (with a link to the e-paper) to be send out to everyone on one of our lists.
So my question is: Can the automated paid feature in Mailchimp do this for us or do we need to code a script with the mailchimp API at the URL to take care of the automated e-mail to the lists? And if the latter which methods should I look into in the documentation?
Not looking for a complete answer, but a pointing in the right direction :)
Google hasn't helped me with the following queries: "send out email to a list when url is visited", "send email campaign to list when url is visited" which is why I now turn to you :)
Thanks in advance
Generally speaking, you could use MailChimp's Goal and Automation features to accomplish something like this. However, you're dealing with a dynamically generated URL that needs to be included in your email. So far, I haven't come accross a way to transfer information from a "Goal page" to MailChimp - other than the data that is transferred automatically by the Goal script.
So I think you're looking at an API job. You'll need to use "Campaigns" methods (http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/).
Please note that creating and sending a campaign are two different steps of the overall process. You'll find the "send" method under "Action" on the same page. Just take the ID returned by the "create" method, feed it into the "send" method and watch the magic happen.
Hope this helps!
Here it is in all it's glory! And it' fixes the issue I had :)
<?php
/**
* Method for communicating with mailchimp API
*
* #param str $method Which url you need to access in the Mailchimp API
* #param str $type Which type of request (POST, GET etc)
* #param array $data Do you need to pass data along aswell in a multi dimensional array?
*
* #author Kenneth Johnsen <Johns3n#gmail.com>
* #return Server Header Response
*/
function request($method,$type, $data = false){
$apiKey = '<API KEY>';
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0'.$method;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($data){
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// GET VARIABLES THAT MIGHT CHANGE DEPENDING ON E-PAPER SUPPLIER:
// -------------------------------------------------------------------------------------
$paper = 'Name of Company';
$replyTo = 'noreply#companyname.com';
$templateId = 65;
// CREATE CAMPAIGN AND RETURN THE ID SO WE CAN EDIT IT ASWELL:
// -------------------------------------------------------------------------------------
$campaign = array(
'type' => 'regular',
'recipients' => array(
'list_id' => '<LIST ID>'
),
'settings' => array(
'subject_line' => 'E-paper for '.$paper.' is now ready!',
'title' => $paper.' E-Paper Notification ('.date("d/m-Y").')',
'from_name' => $paper,
'reply_to' => $replyTo,
)
);
$createCampaign = request('/campaigns','POST',$campaign);
$createCampaign = json_decode($createCampaign);
// EDIT THE CAMPAIGN TO MATCH TEMPLATE ID:
// -------------------------------------------------------------------------------------
$editCampaign = array(
'template' => array(
'id' => $templateId
)
);
$updateCampaign = request('/campaigns/'.$createCampaign->id.'/content','PUT',$editCampaign);
// SCHEDULE THE CAMPAIGN FOR LAUNCH FROM NEAREST QUARTER MINUTE + ANOTHER 30 MINUTES:
// -------------------------------------------------------------------------------------
$time = time();
$time = round($time / (15 * 60)) * (15 * 60) + (30 * 60);
$time = date('i',$time);
$timeSchedule = date('Y-m-dTH:'.$time.':00+01:00');
$schedule = array(
'schedule_time' => $timeSchedule
);
$scheduleCampaign = request('/campaigns/'.$createCampaign->id.'/actions/schedule','POST',$schedule);
var_dump($scheduleCampaign);
I have a problem.
I'm trying to use an API from import.io for manage automatically the stock of products I reselling.
The API returns a value to me and I use this value to determine if the product is in stock or not.
Each group/category uses a different API (because each group is a different origin shop. This code is only for one category, I need to figure out how to make that works for dev the others).
I created this code and I'm trying to make it work in function.php
I have a custom field that has the url source to each product and I want to use it as a parameter to the api.
After checking which group is the product, it gets the data so I can update the stock.
The problem is that I do not know how to update the stock of WooCommerce in this way :O And I'd like to have that verification was done when the single product page was opened by the customer.
Can someone take a look at my code and give me some suggestions?
Thank you!
$userGuid = "c5ed744c-7c10-46d1-9c43-22c6eef5aaca";
$apiKey = "private";
// Issues a query request to import.io
function query($connectorGuid, $input, $userGuid, $apiKey) {
$url = "https://query.import.io/store/connector/" . $connectorGuid . "/_query?_user=" . urlencode($userGuid) . "&_apikey=" . urlencode($apiKey);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"import-io-client: import.io PHP client",
"import-io-client-version: 2.0.0"
));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("input" => $input)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
//This is a custom field
$url_font = apply_filters('custom_url_font', get_post_meta($post->ID, '_url_font', true));
add_action('woocommerce_before_shop_loop_item_title','category_stock');
function category_stock() {
global $woocommerce,$product, $post;
$post_id = $post->ID;
$groupcat = 608; // category id for the this api
$terms = get_the_terms( $post_id, 'product_cat' ); //get taxonamy of the products
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
$catid = $term->term_id;
if($groupcat == $catid) {
$result = query("d9df1137-b402-40ef-b472-35db84684fbe", array(
"webpage/url" => $url_font,//this is the url from the custom field
), $userGuid, $apiKey, false);
if(($result->results[0]->stock)=="INSTOCK")
{
update_post_meta($post->ID, '_stock', '10');
}
else{
update_post_meta($post->ID, '_stock', '0');
}
}
}endif;
}