Skip to content

Instantly share code, notes, and snippets.

@devinsays
Created April 4, 2025 20:51
Show Gist options
  • Save devinsays/210204bf939f9280f18411d9f7d9355f to your computer and use it in GitHub Desktop.
Save devinsays/210204bf939f9280f18411d9f7d9355f to your computer and use it in GitHub Desktop.
DevPress Price Testing - A one file WordPress plugin for testing pricing in WooCommerce.
<?php
/**
* Plugin Name: DevPress Price Testing
* Plugin URI: https://devpress.com
* Description: A plugin to test different pricing variants based on cookies.
* Version: 1.0.0
* Author: DevPress
* Author URI: https://devpress.com
* Text Domain: devpress-price-testing
*
* @package DevPress
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Main plugin class
*/
class DevPress_Price_Testing {
/**
* Singleton instance
*
* @var DevPress_Price_Testing
*/
private static $instance = null;
/**
* Get the singleton instance
*
* @return DevPress_Price_Testing
*/
public static function get_instance() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
// Hook into WooCommerce
add_filter( 'woocommerce_product_get_price', [ $this, 'pricing_test' ], 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', [ $this, 'pricing_test' ], 10, 2 );
}
/**
* Return the value of the pricing test cookie if it is set.
*
* @return string
*/
public static function get_pricing_test_cookie_value() {
$cookie_value = isset( $_COOKIE['pricing_test'] ) ? sanitize_text_field( $_COOKIE['pricing_test'] ) : '';
// Return early if the cookie is not set to one our accepted variants.
$variants = [ 'v1', 'v2' ];
if ( ! in_array( $cookie_value, $variants, true ) ) {
return '';
}
return $cookie_value;
}
/**
* Pricing test.
*
* To test, you can set the cookie in your browser with the following command:
* document.cookie = "pricing_test=v1; path=/";
*
* You can remove the cookie with:
* document.cookie = "pricing_test=; path=/; expires=0";
*
* @param float $price
* @param \WC_Product $product
*
* @return float
*/
public function pricing_test( $price, $product ) {
$cookie_value = self::get_pricing_test_cookie_value();
// If the cookie is not set, return the original price.
if ( $cookie_value === '' ) {
return $price;
}
if ( ! $product instanceof \WC_Product ) {
return $price;
}
$sku = $product->get_sku();
if ( ! $sku ) {
return $price;
}
$price_mapping = [];
// Updated pricing to test in v1 variant.
$price_mapping['v1'] = [
'TEST01' => '50',
];
// If the product sku is in the price mapping array for the variant, return the new price.
if ( isset( $price_mapping[ $cookie_value ] ) && array_key_exists( $sku, $price_mapping[ $cookie_value ] ) ) {
$price = $price_mapping[ $cookie_value ][ $sku ];
}
return $price;
}
}
// Initialize the plugin
DevPress_Price_Testing::get_instance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment