I am working on a plugin for ‘hooking’ an extra payment provider into a checkout system.

I have a class gtpCheckoutData in my function.php which calculates the prices.

In my plugin I want to use data from this gtpCheckoutData class, but if I do that I get a:

Fatal error: Class gtpCheckoutData not found in

My plugin code:

class gtpMollieGateway {
   private $mollie, $price;

   function __construct() {
       $this->mollie    = new Mollie_API_Client;

       // THIS IS THE PROBLEM
       $this->price     = new gtpCheckoutData;

       add_action( 'init', array( $this, 'gtpCreatePayment' ) );
   }

   function gtpCreatePayment() {
       if( isset( $_POST['checkout_submit'] ) ) {
           $payment     = $this->mollie->payments->create(array(
                'amount'        => $this->price->getPrice( 'inclusive' ),

           ));
           header( "Location: " . $payment->getPaymentUrl() );
       }
   }
}

My gtpCheckoutData class in functions.php

class gtpCheckoutData {
    private $tax, $price;

    public function __construct() {
        $this->tax      = get_gtp_option( 'gtp_tax' ) / 100;
        $this->price    = $_SESSION['shopping_cart']['total_price'] + $_SESSION['shopping_cart']['shipping_price'];
        $this->shipping = $_SESSION['shopping_cart']['shipping_price'];
    }

    public function getPrice( $type ) {

        if( isset( $type ) ) {
            switch( $type ) {
                case 'exclusive' : 
                    $totalPrice = $this->price;
                    break;
                case 'tax' :
                    $totalPrice = $this->price * $this->tax;
                    break;  
                case 'inclusive' :
                    $totalPrice = $this->price * ( $this->tax + 1 );
                    break;
            }
            return $totalPrice;
        }
    }
}

2 Answers
2

Plugins are loaded before functions.php. You should include the class in your plugin if possible.

I have had scenarios where a class was part of the theme, but also needed in a plugin where you couldn’t assume the class was included in the theme. In those cases, I simply included the class in both places and wrapped it in a “class exists” check.

Like this:

if(!class_exists('My_Class'))
{
 class My_Class{

    // Class Methods and Properties
 }
}

You could also include the class only once in MU Plugins, which is loaded before the other plugins.

Leave a Reply

Your email address will not be published. Required fields are marked *