Maybe someone could give me a hand resolving this challenge.
I was looking for a solution which would allow me to add products to cart by SKU’s instead of WooCommerce generated ID’s as I would like to use the same products across different CMS systems.
I have stumbled upon the below code, but it seems not to be compatible anymore? Any advice?
<?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 ) );
if ( $product_id ) return $product_id;
return $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' ) );
Source: https://gist.github.com/corsonr/c02b46bd34a8471327bbf3adee6507c8
2
Answers
please try this one, i have include the filter call inside
__constructor
:There is no need to use a custom SQL query, as you can use the
wc_get_product_id_by_sku()
WooCommerce function.Using this function is much more lighter and effective but also takes into account products that are not in trash. Something your current code doesn’t do.
So, this snippet will suffice:
Note: SKU is assumed to be a numerical value
As you can read in the note, the above answer will only work for numerical values, to make this work for all SKU values, you can use as custom query string =
/?add-to-cart-sku=THE-SKU
So you get:
Based on: Allow adding multiple products to the cart via the add-to-cart query string & /includes/class-wc-form-handler.php