Skip to content

Instantly share code, notes, and snippets.

@panoslyrakis
Created June 9, 2017 16:32
Show Gist options
  • Save panoslyrakis/ead99e0ba4e013141f82f7d30dd9e3bf to your computer and use it in GitHub Desktop.
Save panoslyrakis/ead99e0ba4e013141f82f7d30dd9e3bf to your computer and use it in GitHub Desktop.
Appointments+ Update Inventory
<?php
/*
Plugin Name: Appointments+ Update Inventory
Plugin URI: https://premium.wpmudev.org/
Description: Requires Appointments+ and MarketPress. After new appointment it should update product incventory.
Author: Panos Lyrakis @ WPMUDEV
Author URI: https://premium.wpmudev.org/
License: GPLv2 or later
*/
if( ! class_exists( 'WPMUDEV_App_MP_Inventory' ) ){
class WPMUDEV_App_MP_Inventory{
private static $_instance = null;
public static function get_instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new WPMUDEV_App_MP_Inventory();
}
return self::$_instance;
}
private function __construct(){
add_action( 'mp_order/new_order', array( $this, 'maybe_update_inventory' ), 10 );
}
public function maybe_update_inventory( $order ){
$payment_method = mp_get_post_value( 'payment_method', '' );
$cart_info = is_object( $order ) && is_callable( array( $order, 'get_cart' ) )
? $order->get_cart()->get_items()
: ( isset( $order->mp_cart_info ) ? $order->mp_cart_info : array() )
;
if( !is_object( $cart_info ) || epmty( $cart_info ) ){
global $mp_cart;
$cart_info = $mp_cart->get_items();
}
$variation_type = MP_Product::get_variations_post_type();
if ( is_array( $cart_info ) && count( $cart_info ) ) {
foreach ( $cart_info as $cart_id => $count ) {
$variation = get_post( $cart_id );
if ( ! empty( $variation->post_type ) && $variation_type === $variation->post_type && $this->_is_app_mp_page( $variation->post_parent ) ) {
$product_id = $variation->post_parent;
$item = new MP_Product( $product_id );
if ( $item->get_meta( 'inventory_tracking' ) ) {
$stock = $item->get_stock();
// Update inventory
$new_stock = ( $stock - $item->qty );
$item->update_meta( 'inventory', $new_stock );
$item->update_meta( 'inv_inventory', $new_stock );
// Send low-stock notification if needed
if ( $new_stock <= mp_get_setting( 'inventory_threshhold' ) ) {
$item->low_stock_notification();
}
if ( mp_get_setting( 'inventory_remove' ) && $new_stock <= 0 ) {
// Flag product as out of stock - @version 2.9.5.8
wp_update_post( array(
'ID' => $item->ID,
'post_status' => 'draft'
) );
}
}
}
}
}
}
private function _is_app_mp_page ( $product ) {
$product = get_post($product);
$result = is_object( $product ) && strpos( $product->post_content, '[app_' ) !== false
? true
: false
;
// Maybe required for templates
return apply_filters( 'app_is_mp_page', $result, $product );
}
}
add_action( 'plugins_loaded', function(){
$GLOBALS['WPMUDEV_App_MP_Inventory'] = WPMUDEV_App_MP_Inventory::get_instance();
}, 10 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment