Reputation: 53
I'm making a custom payment gateway. The complex parts are going fine but I've now been stuck on something stupid for hours.
I've created custom settings for the gateway without issue, they can be set and saved, but I can't figure out how to recall them in other functions.
If I place var_dump($this->get_option('title'))
within the custom gateway class (which extends WC_Payment_Gateway
) it will show correctly at the top of the settings page. Anywhere else, it won't. I've tried now hundreds of things, like trying to access this class by $this = new WC_Custom_Gateway, making the functions involved public, and utilising init_settings()
.. I'm sure there is a very simple solution, but as a beginner I just cannot see it. I've tried examining the work of others to no avail also.
How can I make those settings available from outside the class where they are defined in?
Upvotes: 4
Views: 5384
Reputation: 253859
Using the following code will allow you to display the necessary data from your payment gateway settings using WC_Payment_Gateways and WC_Payment_Gateway methods this way:
// HERE define you payment gateway ID (from $this->id in your plugin code)
$payment_gateway_id = 'bacs';
// Get an instance of the WC_Payment_Gateways object
$payment_gateways = WC_Payment_Gateways::instance();
// Get the desired WC_Payment_Gateway object
$payment_gateway = $payment_gateways->payment_gateways()[$payment_gateway_id];
// Display saved Settings example:
echo '<p>Title: ' . $payment_gateway->title . '</p>';
echo '<p>Description: ' . $payment_gateway->description . '</p>';
echo '<p>Instructions: ' . $payment_gateway->instructions . '</p>';
// Display all the raw data for this payment gateway
echo '<pre>'; print_r( $payment_gateway ); echo '</pre>';
Alternatively you can also use this shorter way:
// You will have to replace 'bacs' by your payment gateway ID (from $this->id in your plugin code)
$payment_gateway = WC()->payment_gateways->payment_gateways()['bacs'];
// and so on …
Tested and works.
You can also use some WC_Payment_Gateway methods on
$payment_gateway
Upvotes: 11