• Resolved klaivu

    (@klaivu)


    Hi. I’m fairly new to wordpress and coding in general. So bear with me.

    I want to set some transients to prepopulate woocommerce order forms, and to manually set the shopping cart content. The inputs for the transients come from a modified calendar booking plugin which is heavily reliant on ajax. The idea is to grab the field contents from the plugin with jquery, set them as transients, and then use a filter in functions.php to set the field values on the woocommerce checkout page.

    The problem is that I can’t seem to figure out how to set those transients in either a separate php file, or a function inside functions.php. If I use php sessions, everything works, but I don’t really want to do that.

    Here’s my code atm.

    Functions.php:

    function set_thetransients() {
            set_transient('myValue', $_POST['sent_myValue']);
            /* Bunch of other variables set with the $_POST method */
            wp_die();  
        }
    
    add_action( 'wp_ajax_nopriv_set_thetransients', 'set_thetransients' );
    add_action( 'wp_ajax_set_thetransients', 'set_thetransients' );
    
    add_filter('woocommerce_checkout_get_value', function($input, $key ) {
        global $current_user;
        switch ($key) :
            case 'billing_first_name':
                return $current_user = get_transient('myValue');
            break;
    	/ * Bunch of other fields get set the same way */
        endswitch;
    }, 10, 2);

    Within the booking calendar js file, when submitting the form:

    var ajaxurl = '/Site folder name/wp-admin/admin-ajax.php';
    jQuery.post(ajaxurl, {sent_myValue: $("#form_field_id").val() 
    /* Bunch of other fields grabbed with jQuery */   });
Viewing 2 replies - 1 through 2 (of 2 total)
  • Don’t forget to sanitize the inputs and check for user capabilities and a nonce, or your form will invite hackers.
    For AJAX in WP, you have to set the action variable. In your case, it should be ‘set_thetransients’ which is the suffix on the action name of your add_action call.

    Thread Starter klaivu

    (@klaivu)

    Oh my god, that was so simple. Also forgot to put the variable names in quotes in the ajax call. Thanks a lot!

    I will sanitize the inputs, and add a nonce. Looks like I ought to pair the transients with cookies as well, since I want them to be specific to the user. There’s always a lot more to learn it seems.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to set transients with ajax?’ is closed to new replies.