Add WooCommerce Product to Cart From URL Using Products SKU
I am working on a personal project for Automattic, and in this project I needed to tweak the way WooCommerce adds products to cart.
Basically, when you add a product to cart, you probably noticed it if Ajax isn’t enabled in your shop, your are redirected to page having the following URL structure:
http://mysite.com/?add-to-cart=XX
Where XX is the product added to cart ID. I wanted to be able to use the SKU in the URL instead of the product ID, in other words I wanted this:
http://mysite.com/?add-to-cart=SKU
So, I wrote this plugin:
<?php
/**
* Plugin Name: WooCommerce: Add Product to Cart by SKU
* Plugin URI: http://remicorson.com
* Description: Just a demo!
* Version: 1.0
* Author: Remi Corson
* Author URI: http://remicorson.com/
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* WC Product Add to Cart by SKU class
*/
class WC_Add_to_Cart_by_SKU {
/**
* Constructor
*/
public function __construct() {
define( 'WC_ADD_TO_CART_BY_SKU_VERSION', '1.0' );
define( 'WC_ADD_TO_CART_BY_SKU_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) );
define( 'WC_ADD_TO_CART_BY_SKU_PLUGIN_URL', untrailingslashit( plugins_url( basename( plugin_dir_path( __FILE__ ) ), basename( __FILE__ ) ) ) );
}
/**
* get_product_id_by_product_sku()
*
* Return product ID from product SKU
*/
public function get_product_id_by_product_sku( $add_to_cart ) {
global $wpdb;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $add_to_cart ) );
return $product_id ?? $add_to_cart;
}
}
add_filter( 'woocommerce_add_to_cart_product_id', array( new WC_Add_to_Cart_by_SKU(), 'get_product_id_by_product_sku' ) );
Now, I can type, let’s say http://mysite.com/?add-to-cart=5678 and the product having the SKU equal to 5678 will be added to cart. If no product has this SKU, then the product having 5678 as its ID will be added to cart.
Please note: due to a security check within WooCommerce, that method will work only with SKU containing numbers only. Letters aren’t accepted.