How to set payment method in woocommerce via php?

Member

by mac , in category: PHP CMS , 8 months ago

How to set payment method in woocommerce via php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 8 months ago

@mac 

To set a payment method in WooCommerce via PHP, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function add_payment_gateway() {
    add_filter( 'woocommerce_payment_gateways', 'add_custom_payment_gateway' );
    
    function add_custom_payment_gateway( $gateways ) {
        $gateways[] = 'WC_Custom_Payment_Gateway';
        return $gateways;
    }
}

add_action( 'plugins_loaded', 'add_payment_gateway' );

class WC_Custom_Payment_Gateway extends WC_Payment_Gateway {
    public function __construct() {
        $this->id = 'custom_payment_gateway';
        $this->method_title = 'Custom Payment Gateway';
        $this->title = 'Custom Payment Gateway';
        $this->has_fields = true;
        $this->init_form_fields();
        $this->init_settings();
        
        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
    }

    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => 'Enable/Disable',
                'type' => 'checkbox',
                'label' => 'Enable Custom Payment Gateway',
                'default' => 'yes'
            )
        );
    }

    public function process_payment( $order_id ) {
        $order = wc_get_order( $order_id );
        $order->update_status( 'processing' );
        $order->reduce_order_stock();
        WC()->cart->empty_cart();

        return array(
            'result' => 'success',
            'redirect' => $this->get_return_url( $order )
        );
    }
}


You can add this code snippet to your theme's functions.php file or create a custom plugin for it. This code creates a custom payment gateway called "Custom Payment Gateway" that can be enabled or disabled in the WooCommerce settings. When a customer selects this payment method at checkout, the order status will be updated to "processing" and the stock will be reduced.