admin-ajax.php not working properly on subdomains

Don’t bother with the complicated cookie/ajax nonsense, use a REST API!

We’ll use dependency injection and RESTful APIs to remove the cookies and simplify your AJAX code.

First things first, lets turn this into a REST API:

class Stuff {
    public function __construct() {
        add_action( 'rest_api_init', function () {
                register_rest_route( 'soothsayer/v1', '/current_rate/', array(
                        'methods' => 'GET',
                        'callback' => [ $this, 'get_original_price' ]
                ) );
        } );
    }

    public function get_original_price( $request ) {
        $variation_id = $request['variation_id'];
        $original_price = get_post_meta( $variation_id, "_regular_price", true);

        $currency = $request['currency'];

        $ratesCurrency = $this->currencyRates( $currency );
        $priceAfterCurrency = $original_price*$ratesCurrency;
        return $priceAfterCurrency;
    }

    private function currencyRates( $currency ) {
        global $wpdb;
        $rate = 1;

        $name="wcumcs_exchange_rate_".$currency;
        $selectRate = $wpdb->get_results("SELECT option_value FROM ".$wpdb->prefix."options WHERE option_name="".$name."" LIMIT 1;");

        foreach ($selectRate as $row) {
            $rate = $row->option_value;    
        }
        return $rate;
    }
}

Now we have a REST endpoint! Notice how I:

  • Fixed the indenting, or rather my editor did it automatically without effort, and so should yours!
  • Used dependency injection to grab the currency. currencyRates doesn’t need to know where the currency value came from, it’s passed as a parameter, now it’ll work for any currency no matter how it was acquired, not just the one set in the cookie
  • Currency is now a parameter, javascript can read cookies just fine, and now your request is 100% cachable. This is now 1000% better for performance
  • Notice the $request object passed into get_original_price, this will give you all the details

How do I use this?

jQuery.get(
    'https://example.com/wp-json/soothsayer/v1/current_rate',
    {
        'variation_id' => 1,
        'currency' => 'USD'
    },
    function( data ) {
        // success?
    }
);

Or even by visiting https://example.com/wp-json/soothsayer/v1/current_rate?variation_id=1&currency=USD

An Optimisation

This is not how you fetch an option from the options table:

    global $wpdb;
    $rate = 1;

    $name="wcumcs_exchange_rate_".$currency;
    $selectRate = $wpdb->get_results("SELECT option_value FROM ".$wpdb->prefix."options WHERE option_name="".$name."" LIMIT 1;");

This is how you do it:

$rate = get_option( 'wcumcs_exchange_rate_'.$currency, 1 );

If you need to fetch multiple options you can do that via get_option with no parameters to grab an array