I try to call a (public static) function of a plugin in my functions.php, but that doesn't work. I tried this code:
include_once( ABSPATH . '/wp-content/plugins/atum-multi-inventory/classes/Models/Inventory.php' );
add_action('woocommerce_before_add_to_cart_button', 'getMainInventory', 99 );
function getMainInventory () {
global $product;
$proid = $product->id;
if(function_exists('get_product_main_inventory')){
$test = get_product_main_inventory( $proid );
echo $test;
}
else {
echo "failed";
}
}
But I always get "failed" back although the plugin is activated. My product is a simple product.
Here is the function I try to call:
/EDIT: Added the namespace and use statements below:
namespace AtumMultiInventory\Models;
defined( 'ABSPATH' ) || die;
use Atum\Components\AtumCache;
use Atum\Components\AtumOrders\AtumOrderPostType;
use Atum\Inc\Globals;
use Atum\Inc\Helpers as AtumHelpers;
use AtumMultiInventory\Legacy\InventoryLegacyTrait;
use AtumMultiInventory\Inc\Helpers;
class Inventory {
/**
* Get the Main Inventory for the specified product
*
* @since 1.0.0
*
* @param int $product_id Must be original translation.
*
* @return MainInventory
*/
public static function get_product_main_inventory( $product_id ) {
$cache_key = AtumCache::get_cache_key( 'product_main_inventory', $product_id );
$main_inventory = AtumCache::get_cache( $cache_key, ATUM_MULTINV_TEXT_DOMAIN, FALSE, $has_cache );
if ( ! $has_cache ) {
global $wpdb;
$product_id = apply_filters( 'atum/multi_inventory/product_id', $product_id );
// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
$query = $wpdb->prepare( "
SELECT id
FROM $wpdb->prefix" . self::INVENTORIES_TABLE . '
WHERE `product_id` = %d AND `is_main` = 1
', $product_id );
// phpcs:enable
$main_inventory_id = absint( $wpdb->get_var( $query ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$main_inventory = Helpers::get_inventory( $main_inventory_id, $product_id, TRUE );
AtumCache::set_cache( $cache_key, $main_inventory, ATUM_MULTINV_TEXT_DOMAIN );
}
return $main_inventory;
}
}
Can anybody help me please?
You should use like this:
add_action('woocommerce_before_add_to_cart_button', 'getMainInventory', 99 );
function getMainInventory () {
global $product;
use AtumMultiInventory\Models\Inventory;
$proid = $product->id;
include_once( ABSPATH . '/wp-content/plugins/atum-multi-inventory/classes/Models/Inventory.php' );
if(method_exists(Inventory::class, 'get_product_main_inventory' )){
$test = Inventory::get_product_main_inventory( $proid );
echo $test;
}
else {
echo "failed";
}
}
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).