Skip to content

Instantly share code, notes, and snippets.

@helgatheviking
Last active December 21, 2018 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save helgatheviking/a8802255167751a5dd746f83cdfc8716 to your computer and use it in GitHub Desktop.
Save helgatheviking/a8802255167751a5dd746f83cdfc8716 to your computer and use it in GitHub Desktop.
Force NYP products to respect "sold individually" regardless of price. Requires WC 2.6.3
<?php
/**
* Plugin Name: WooCommerce Name Your Price Sold Individually
* Plugin URI: https://gist.github.com/helgatheviking/a8802255167751a5dd746f83cdfc8716
* Description: Stricter enforcement of "Sold Individually" for NYP items
* Version: 1.2.0
* WC requires at least: 2.6.3
* Author: Kathy Darling
* Author URI: http://kathyisawesome.com/
*
* Copyright: © 2016 Kathy Darling
* License: GNU General Public License v3.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/**
* Attach hooks only when NYP is active.
*/
function wc_nyp_sold_individually_init() {
add_filter( 'woocommerce_cart_id', 'wc_nyp_force_sold_individually', 10, 5 );
}
add_action( 'wc_name_your_price_loaded', 'wc_nyp_sold_individually_init' );
/**
* Regenerate a unique ID for the cart item being added.
*
* @param string cart item key.
* @param int $product_id - id of the product the key is being generated for.
* @param int $variation_id of the product the key is being generated for.
* @param array $variation data for the cart item.
* @param array $cart_item_data other cart item data passed which affects this items uniqueness in the cart.
* @return string
*/
function wc_nyp_force_sold_individually( $cart_id, $product_id, $variation_id, $variation, $cart_item_data ) {
// Get the product.
$product = wc_get_product( $variation_id ? $variation_id : $product_id );
if ( $product->is_sold_individually() && WC_Name_Your_Price_Helpers::is_nyp( $product ) ){
$id_parts = array( $product_id );
if ( $variation_id && 0 != $variation_id ) {
$id_parts[] = $variation_id;
}
if ( is_array( $variation ) && ! empty( $variation ) ) {
$variation_key = '';
foreach ( $variation as $key => $value ) {
$variation_key .= trim( $key ) . trim( $value );
}
$id_parts[] = $variation_key;
}
$cart_id = md5( implode( '_', $id_parts ) );
}
return $cart_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment