Skip to content

Instantly share code, notes, and snippets.

@panoslyrakis
Created May 27, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panoslyrakis/c9fce8a68523245bd1c0b4554f5eaccb to your computer and use it in GitHub Desktop.
Save panoslyrakis/c9fce8a68523245bd1c0b4554f5eaccb to your computer and use it in GitHub Desktop.
A way to control MarketPress product prices so they don't get set to <= 0
<?php
/*
Plugin Name: MarletPress Control Product Prices
Plugin URI: https://premium.wpmudev.org/
Description: A way to control MarketPress product prices so they don't get set to <= 0
Author: Panos Lyrakis @ WPMUDEV
Author URI: https://premium.wpmudev.org/
License: GPLv2 or later
*/
if( ! class_exists( 'WPMUDEV_MP_Price_Control' ) ){
class WPMUDEV_MP_Price_Control{
private static $_instance = null;
public static function get_instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new WPMUDEV_MP_Price_Control();
}
return self::$_instance;
}
private function __construct(){
add_action( "updated_post_meta", array( $this, 'updated_product_meta' ), 999, 4 );
}
public function updated_product_meta( $meta_id, $object_id, $meta_key, $_meta_value ){
$post = get_post( $object_id );
if( $post->post_type != MP_Product::get_post_type() || $meta_key != 'regular_price' || $_meta_value == '' ){
return;
}
if( $_meta_value <= 0 ){
$previous_valid_price = $this->get_previous_valid_price( $object_id );
$this->force_product_price( $meta_id, $object_id, $meta_key, $previous_valid_price );
}
else{
$meta_key = '_wpmudev_mp_regular_price_backup';
update_post_meta( $object_id, '_wpmudev_mp_regular_price_backup', $_meta_value );
}
}
public function force_product_price( $meta_id, $object_id, $meta_key, $_meta_value ){
$meta_type = 'post';
if ( !$meta_key || ! is_numeric( $_meta_value ) )
return false;
if ( !$object_id = absint($object_id) )
return false;
if ( ! $table = _get_meta_table($meta_type) )
return false;
global $wpdb;
$column = esc_sql($meta_type . '_id');
$id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
// expected_slashed ($meta_key)
$meta_key = stripslashes($meta_key);
$data = array(
'meta_value' => $_meta_value
);//compact( 'meta_value' );
$where = array( $column => $object_id, 'meta_key' => $meta_key );
$wpdb->update( $table, $data, $where );
wp_cache_delete($object_id, $meta_type . '_meta');
}
public function get_previous_valid_price( $post_id ){
return get_post_meta( $post_id, '_wpmudev_mp_regular_price_backup', true );
}
}
add_action( 'plugins_loaded', function(){
$GLOBALS['WPMUDEV_MP_Price_Control'] = WPMUDEV_MP_Price_Control::get_instance();
}, 10 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment