Home > front end >  Directly call ajax function via php
Directly call ajax function via php

Time:06-28

in woocommerce you can activate the payment items via toggle. this is build with ajax.

In chrome browser, network tab i can see the payload object which was send to "wp-admin/admin-ajax.php"

{
    action: woocommerce_toggle_gateway_enabled
    security: 33212389b2
    gateway_id: cheque
  }

Is it possible in wordpress directly access the action "woocommerce_toggle_gateway_enabled" via php and set the value?

CodePudding user response:

It's an action for AJAX requests. It's not meant to be used directly in php.

You need to extract the update parts from the action function and create your own function.

https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-ajax.html#source-view.3076

you basically need this code section and remove the wp_send_json_...() and wp_die() functions and you need to pass the gateway_id in your implementation.

    // Load gateways.
    $payment_gateways = WC()->payment_gateways->payment_gateways();

    // PASS THE GATEWAY ID HERE
    $gateway_id = 'gateway_id';

    foreach ( $payment_gateways as $gateway ) {
        if ( ! in_array( $gateway_id, array( $gateway->id, sanitize_title( get_class( $gateway ) ) ), true ) ) {
            continue;
        }
        $enabled = $gateway->get_option( 'enabled', 'no' );
        $option  = array(
            'id' => $gateway->get_option_key(),
        );

        if ( ! wc_string_to_bool( $enabled ) ) {
            if ( $gateway->needs_setup() ) {
                wp_send_json_error( 'needs_setup' );
                wp_die();
            } else {
                do_action( 'woocommerce_update_option', $option );
                $gateway->update_option( 'enabled', 'yes' );
            }
        } else {
            do_action( 'woocommerce_update_option', $option );
            // Disable the gateway.
            $gateway->update_option( 'enabled', 'no' );
        }

        do_action( 'woocommerce_update_options' );
        wp_send_json_success( ! wc_string_to_bool( $enabled ) );
        wp_die();
    }

CodePudding user response:

In WordPress if there's Ajax action "woocommerce_toggle_gateway_enabled" then there should be somewhere:

<?php
add_action('wp_ajax_woocommerce_toggle_gateway_enabled', 'my_action');

function my_action()
{
    global $wpdb; // this is how you get access to the database
    $whatever = intval($_POST['whatever']);
    $whatever  = 10;
    echo $whatever;
    wp_die(); // this is required to terminate immediately and return a proper response
}

So I guess you could call my_action() but it seems they all should end with echo and die so it would take some adjustments, probably.

  • Related