Using WooCommerce REST API with our plugins

WooCommerce REST API is useful for creating headless shops and automating processes . Here we will show couple of examples where you can see how our plugins can be managed via Woo REST api like how to retrieve product data and how to create new auction product using WooCommerce REST API v3.

First you will need to go to WooCommerce Settings -> Advanced and enable REST API then create client key and secret, then assign permissions you need for your use case.

Once this is completed go to https://github.com/Automattic/wp-rest-php-lib and download their PHP lib. Extract so you have folder structrue something like https://www.yourwebsite.com\api\WooCommerce and in \api\ create test_api.php file. Their lib is intented to be used with Composer and we advise that but in the example we will not use Composer in order to have as less prerequisites as possible.

Code example for WooCommerce REST API – listing auctions and creating new auction product

Since WooCommerce REST API can retrieve custom product types we will use type parameter to retrieve all auction products available in our Woo product list. Copy paste into your test_api.php file following code:

<?php

include_once(__DIR__ . '/WooCommerce/HttpClient/BasicAuth.php');
include_once(__DIR__ . '/WooCommerce/HttpClient/HttpClient.php');
include_once(__DIR__ . '/WooCommerce/HttpClient/HttpClientException.php');
include_once(__DIR__ . '/WooCommerce/HttpClient/OAuth.php');
include_once(__DIR__ . '/WooCommerce/HttpClient/Options.php');
include_once(__DIR__ . '/WooCommerce/HttpClient/Request.php');
include_once(__DIR__ . '/WooCommerce/HttpClient/Response.php');
include_once(__DIR__ . '/WooCommerce/Client.php');

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
	'https://www.yourwebsite.com',
	'your_client_key',
	'your_client_secret',
	[
	   'wp_api'  => true,
	   'version' => 'wc/v3',           
	]
);
$data = [
    'type' => 'auction' // get all auction products
];
print_r( $woocommerce->get( 'products', $data) );

Examples how to get and create auction products (for WooCommerce Simple Auctions) using WooCommerce API:

$data = [
    'name' => 'New Auction',
    'type' => 'auction',
    'status' => 'draft', // status can be: draft, published, pending

    'meta_data' => array(
        [ 'key' => '_auction_start_price', 'value' => '7.99' ],             // starting bid
        [ 'key' => '_auction_bid_increment', 'value' => '1.5' ],            // min bid increment
        [ 'key' => '_regular_price', 'value' => '2900' ],                   // buy now price
        [ 'key' => '_auction_reserved_price', 'value' => '2000.0' ],       // reserve price
        [ 'key' => '_auction_dates_from', 'value' => '2022-02-11 00:00' ],  // start date
        [ 'key' => '_auction_dates_to', 'value' => '2022-02-27 00:00' ],    // end date
        [ 'key' => '_auction_proxy', 'value' => 'no' ], // proxy auction, yes | no   
        [ 'key' => '_auction_sealed', 'value' => 'no' ], // sealed auction, yes | no        
    ),

    'description' => 'This is sample auction added via WooCommerce API',
    'short_description' => 'Sample api auction.',    
];


print_r( $woocommerce->post( 'products', $data ) );

Examples how to get and create lottery products (for plugin WooCommerce Lottery) using WooCommerce API:

$data = [
    'type' => 'lottery' // get all lottery products
];
print_r( $woocommerce->get( 'products', $data) );
$data = [
    'name' => 'New Lottery',
    'type' => 'lottery',
    'status' => 'draft',    // status can be: draft, published, pending

    'meta_data' => array(       
        
        [ 'key' => '_min_tickets', 'value' => '30' ], // min number of tickets needed
        [ 'key' => '_max_tickets', 'value' => '100' ], // max number of tickets
        [ 'key' => '_max_tickets_per_user', 'value' => '100' ], // max per user (optional)
        [ 'key' => '_lottery_num_winners', 'value' => '1' ], // number of winners        
        [ 'key' => '_lottery_price', 'value' => '20.99' ], // ticket price
        [ 'key' => '_lottery_sale_price', 'value' => '15.99' ], // sale price (optional)
        [ 'key' => '_lottery_dates_from', 'value' => '2022-02-11 00:00' ], // start date
        [ 'key' => '_lottery_dates_to', 'value' => '2022-02-27 00:00' ], // end date        
    ),
    'description' => 'This is sample lottery added via WooCommerce API',
    'short_description' => 'Sample api lottery.',
    
];


print_r( $woocommerce->post( 'products', $data ) );

Examples how to get and create group buy / deal products (for plugin WooCommerce Lottery) using WooCommerce API:

$data = [
    'type' => 'groupbuy' // get all group buy / deal products
];


print_r( $woocommerce->get( 'products', $data) );
$data = [
    'name' => 'New Group Buy',
    'type' => 'groupbuy',
    'status' => 'draft',    // status can be: draft, published, pending
    
    'meta_data' => array(       
        
        [ 'key' => '_groupbuy_min_deals', 'value' => '30' ], // min deals sold needed
        [ 'key' => '_groupbuy_max_deals', 'value' => '100' ], // max deals sold
        [ 'key' => '_groupbuy_max_deals_per_user', 'value' => '100' ], // max per user (optional)
        [ 'key' => '_groupbuy_price', 'value' => '10.99' ], // deal price
        [ 'key' => '_groupbuy_regular_price', 'value' => '21.99' ], // regular price
        [ 'key' => '_groupbuy_dates_from', 'value' => '2022-02-11 00:00' ], // start date
        [ 'key' => '_groupbuy_dates_to', 'value' => '2022-02-27 00:00' ], // end date
        
    ),
    'description' => 'This is sample group buy added via WooCommerce API',
    'short_description' => 'Sample api group buy.',
    
];


print_r( $woocommerce->post( 'products', $data ) );

How can you limit number of produtcs retrieved? You can use per_page attribute in $data like below (search, offset, order, order by etc options are available useful for paging and filtering) – all available parameters are listed here https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-products:

$data = [
    'per_page' => 1,    // api will return only 1 auction product
    'type' => 'auction'
];


print_r( $woocommerce->get( 'products', $data) );

Complete REST API documentation can be found on https://woocommerce.github.io/woocommerce-rest-api-docs/. If you have additional questions on how WooCommerce REST API works with WooCommerce Simple Auctions, WooCommerce Lottery and WooCommerce Group Buy please open ticket here or contact us.

How to Create Entry Lists for WooCommerce Lottery and Pick Number addon?

For entry lists to work you will need WooCommerce Lottery plugin and WooCommerce Lottery / Raffles Pick Ticket Number Mod addon since entry lists make sense only with ticket numbers and feature is implemented in Pick Number addon in version v2.1.0. Make sure you have latest version of WooCommerce Lottery and Pick Number mod addon.

Now you need to create new blank page by going to Pages -> Add New. Just add page title for example “Entry Lists” and click publish.

Next step is to go to WooCommerce Settings then click Lottery tab. Scroll down to WC Lottery Entry Page dropdown and select there “Entry Lists” page which you published moment ago. Save settings and go to “Entry Lists” page to see all active lotteries.

woocommerce lottery entry lists page setup how to

Clicking on specific lottery will lead you to its entry page – see our demo website here.

Change number of products displayed per page

One of the common inqury in our support tickets, unrelated to plugin functionality, was how to change number of products displayed on WooCommerce product archive page.

Most themes come with settings page where you can change number of producs displayed, in fact you can change number of rows and columns per page but there are also themes without that option.

So to do that you need to add code to your child theme’s functions.php file. Avoid adding custom code directly to your parent theme’s functions.php file as this will be wiped entirely when you update the theme.

This solution requires you to have your shop page display (WooCommerce > Product catalog set to “Show products”). Code snippet is below (snippet is from woocommerce.com):

/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  // $cols contains the current number of products per page based on the value stored on Options –> Reading
  // Return the number of products you wanna show per page.
  $cols = 9;
  return $cols;
}

Black Friday / Cyber Monday discount and coupon code, current versions update

We have nice promo running this week (until 30th Nov 2021) – all items in our store are 40% off. You can use coupon code blackfriday21 to get the discount once you are on checkout page.

Our current versions for plugins: WooCommerce Lottery v2.1.2, Woo Lottery Pick Number Mod addon v2.1.0, Woo Simple Auctions v2.0.6. If you don’t have those versions we recommend you to update.

Why we use and suggest real cronjobs for our plugins (and WordPress)?

wordpress_cronjobs_real_cronjob

In this article we’ll explain benefits of using real cronjobs instead of interal WordPress cron.

First of all, a couple words about why do we have a need for cronjobs in our plugins like Simple Auctions, Lotteries and Group Buy. Custom product types (auctions, lotteries and deals) in these plugins have start and end timestamp and we need to have reliable way to fullfill start and end timestamps for auctions, lotteries and group buy / deals on time and to send email notifications in specified intervals (for example twice daily).

We cannot use WordPress cronjobs because they are not reliable and depend on visitor accessing your website. That means if your WordPress has say 3 visitors a day it will run internal WP cron 3 times that day (and we will be able to close auction only 3 times a day and not on end datetime set in auction). So if there is no site activity for say 3 days, the cron will not be triggered for 3 days but next time you have visit on your website.

Another problem – if there are a lot of pending tasks to be run by WP internal cron, user will have to wait for those to be executed and then website will load for user meaning bad user experience due to slow loading times (which are caused by WP internal cronjob running and executing pending tasks). Real server cronjobs do not depend on website activity and are run in fixed defined intervals as set in cronjob config.

It’s better to have maintenance tasks running in background by cron than by your visitors – one more reason to use either real cronjobs or external service like EasyCron. EasyCron has nice tutorial how to setup cronjobs for Simple Auctions (also useful for Lotteries and Group Buy plugin).

If your hosting company (hosting provider) does not support one minute cronjobs we suggest that you move your website to better (serious) hosting company (or use service like EasyCron).

One performance suggestion for your WordPress site – since you are allready setting up cronjobs, you could also setup main WP cron to be run by real cronjob (or EasyCron) so your visitors don’t load WP cron at all. You need to edit wp-config.php file and add this line:

define('DISABLE_WP_CRON', true);

Then set this cron (use either wget or curl – whatever your hosting supports, just don’t use both at same time!):


/usr/bin/wget -q -O https://domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

OR 

/usr/local/bin/curl --silent https://domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

Where you need to replace domain.com with your actual domain to your WordPress site and make sure to have right path to wget or curl (safest way to find out those is to contact your hosting provider).

With these in place you will have reliable way to do WordPress maintenance cron tasks and your visitors will have better user experience because your WordPress will load a bit faster since users will not run WP cron on every website access.