WooCommerce REST API – Import products from JSON

I had a task to create a PHP script to import simple and variable products from JSON file using the WooCommerce REST API. Thought it might be worth sharing with others because I couldn’t find much information about products import from JSON using the API.

To make it easier to understand, I created a simple JSON file with one simple product and one variable product that have two product variations. You can get all files from Github repository.

products.json

Getting started

What you need to do is download a PHP wrapper for the WooCommerce REST API. You can download it using composer from https://packagist.org/packages/automattic/woocommerce If you don’t have composer yet, then you can download it from https://getcomposer.org

Setup

Setup for the new WP REST API integration (WooCommerce 2.6 or later):

1. Parse JSON

Convert JSON string to PHP array.

2. Get all product attributes from JSON

We need to get all product attributes names and values from JSON file.

3. Get products and variations from JSON for importing

4. Merge products and product variations

Used to loop through products, then loop through product variations.

5. A simple function to print status message

Import products to WooCommerce using the API

You can find the script on Github repository

My first package for Laravel – Google Safe Browsing Lookup (v4)

I’ve been working on an exciting project, and one of the first task was to integrate Google Safe Browsing into the project. The Safe Browsing APIs (v4) let you check URLs against Google’s constantly updated lists of unsafe web resources. However, I couldn’t find a working package for Laravel 5.4 so I decided to create my own and share it on github and packagist.

Installation

Run the following from the Terminal:

Next, add your new provider to the providers array of config/app.php:

Finally, add aliases to the aliases array of config/app.php:

Preparation

You need to get your API key from Google Safe Browsing API.

Publish the config file.

Set your API key in YOUR-APP/config/google_safe_browsing.php

Usage

More examples

License

The package is licensed under the GPL v3 License.

Writing secure code in WordPress and preventing the most common security vulnerabilities

The number of vulnerabilities discovered in WordPress plugins and themes is quite impressive. If you take a look at public exploits databases, you’ll see new vulnerabilities discovered every week.

According to the most recent data (source: ThreatPress WordPress plugins and themes vulnerabilities database), the most common vulnerabilities in WordPress plugins and themes are XSS (Cross-site Scripting) and CSRF (Cross-Site Request Forgery). Less common types of vulnerabilities are SQL Injection, RFI (Remote File Inclusion), LFI (Local File Inclusion), Arbitrary File Upload, Directory Traversal.

Security is one of the most important things to keep in mind. If you develop WordPress plugins and themes, then you should follow the best security practices (See WordPress Codex: Validating Sanitizing and Escaping User Data). There are plenty of examples about every vulnerability exploitation. If you are not familiar with such types of attacks, then I’d recommend watching step by step guides on Youtube.

How to prevent attacks and secure your code in WordPress?

Validate data. Use the right helper functions to sanitize and escape data.

Validation – Verification that something is correct or conforms to a certain standard (such as a string contains numbers and letters).
Sanitization – Is a technique to modify the input to ensure that it is valid (such as doubling single quotes).
Escaping – Converting the special HTML characters to HTML entities (makes certain characters like ‘, “, and > don’t break anything and to prevent XSS).

The difference between sanitizing and escaping is that when you save something to the database, then you sanitize all data collected from $_POST, $_GET and $_REQUEST. When you output data from the database or from user input, then you escape it.

What is XSS (Cross-site Scripting) and how to prevent it?

An XSS vulnerability enables attackers to inject client-side scripts into web pages viewed by users. The first thing you need to do is to sanitize user input. In many cases you can use sanitize_text_field( $string ) function. This function will convert HTML characters to entities, strip all tags and remove extra whitespace. If you need to sanitize email, then you should use sanitize_email( $email ). For the full list of functions, go to WordPress Codex > Data Validation. When you need to output your data – escape it. It will also prevent XSS vulnerabilities. WordPress has a few helper functions such as esc_attr(), esc_html(), esc_url() and more (see Codex).

What is CSRF (Cross-Site Request Forgery) and how to prevent it?

Cross-site request forgery (CSRF) is an attack vector that tricks a web browser into executing an unwanted action in an application to which a user is logged in. To prevent CSRF, you need to use nonces. A nonce is a “number used once” to help protect URLs and forms from particular types of misuse.

How to prevent SQL injection?

Use only safe $wpdb API methods to insert, update and delete from the database. All data in SQL queries must be SQL-escaped before the SQL query is executed. A good function for that is esc_sql().

Safe methods are:
$wpdb->insert()
$wpdb->update()
$wpdb->delete()

Use other methods only with $wpdb->prepare(). This helps prevent SQL injections.

What I learned from doing customer support for WordPress products and why it’s great

I’m always involved in customer support. I’m providing support for my own plugins and helping others in forums. When I was working for other companies, we had a practice where every week a team member jumps into the support queue and answers some complex tickets. First of all, customer support is rewarding. I’ll tell you why.

Happy customers = more sales

A long-term happy customer will mean that all that hard work you did to resolve the issues will turn into profits and loyalty. “On average, loyal customers are worth up to 10 times as much as their first purchase.” (Source: White House Office of Consumer Affairs)

You can understand your customers

By providing support you can identify areas where your customers are struggling. You can improve the documentation. You can bring new stuff through positive recommendations and improve the product.

You can get testimonials

Testimonials are important to business success. If you provide excellent customer support, then you can get great testimonials. When your potential customers visit your website for the first time, they will look for testimonials.

You can improve your debugging skills

It’s a great way to improve your ability to debug existing code. Answering complex tickets requires time and a lot of debug work.

Make new friends

Doing things that make people feel good and significant will turn into a friendly relationship. They’ll want to keep in touch with you.

How to extend search for custom post types in WordPress admin

I recently had to extend the search to include custom fields in WordPress admin. I created a custom post type called “document” and a few custom fields such as “_file_name” and “_url”. Unfortunately, it’s not possible to search by custom field value in WordPress admin, so I had to hook into the native WordPress search and tweak it.

WordPress admin search

In order to change the search query, you need to hook into pre_get_posts action. The pre_get_posts action gives developers access to the $query object by reference (Read more at WordPress Codex).

WordPress admin search

Here’s the code. You can change $post_type and $custom_fields according your needs.

How to create a jQuery autocomplete drop down in WordPress

The autocompletion allows users to select from a pre-populated list of suggestions as they type. There are a number of jQuery autocomplete plugins. I’ll create an autocomplete from the post titles and redirect to a blog post based on selected option value. I’ll use jQuery UI autocomplete since it’s already included in WordPress. You can find demo: here.

Firstly, we need to enqueue jQuery UI and autocomplete libraries.

Secondly, we need to add a simple textbox in the front-end. I’ll attach jQuery UI autocomplete to it. I added a shortcode to output HTML text input field.

Also, add some CSS to make it nicer.

Autocomplete dropdown

Lastly, we need to enable autocomplete on our text input field and define the data to use. The datasource is a JavaScript array and you can define whatever you want – posts, pages, WooCommerce products, users and so on. If you have a lot of posts, then you should load a JSON file as source. Some useful links to documentation: option source, event select.

You can move JavaScript code to an external file.

Also, you can customize the select drop down with _renderItem method.

How to add custom product sorting options in WooCommerce

By default, WooCommerce comes with 6 sorting options:

  • Sort by popularity
  • Sort by average rating
  • Sort by newness
  • Sort by price: low to high
  • Sort by price: high to low

In this example, I’ll add an extra option to sort by sale status.

Adding a new sorting option

woocommerce_catalog_orderby hook gives you control over the default sorting options to display. In order to add a new option, you need to add it to the current options array.

Code:

Now add the following code to order by the _sale_price custom field.

Code:

Advanced sorting

However, if your sorting needs are more advanced, then you can hook into pre_get_posts instead of woocommerce_get_catalog_ordering_args.

The pre_get_posts hook gives developers access to the $query object and possibility to modify the query. It’s really powerful and useful for altering the main loop and creating custom queries. See the docs here.

In this example, we’ll show products from a given category ‘Cars’ and sort them by sale status.

Code:

How to prevent CSS caching and load the most recent version of a file after updating

When working with clients you need to make sure any CSS changes are loading and website is updated. Every time a browser loads a webpage it has to download a number of files, including CSS and JavaScript. A common solution is to use CSS versioning. Adding a version number to the CSS file will let the server know this is a new file. You can automatically version your CSS files by adding a last modified timestamp to the end of the file name like /css/style.css?ver=1469128847

A solution in WordPress:

Version number is a parameter of wp_enqueue_style().

Codex:

We’ll use the filemtime() function to return the last time the file content was modified.

Code:

Result: