Aim - I've trying to run a query based on which category is selected from the dropdown.

I figure the best way to do this, is to dynamically use AJAX and pass the category value held by a variable to the WordPress query.

I've successfully created a dropdown menu which is populated via an ACF user meta data, so I'm needing to pass the selected value to the query making it update the results each time a new category is selected.

Code that generates the dropdown -


        $field_key = "field_5481bc1472b1d";
        $field = get_field_object($field_key);

        if( $field )
            echo '<select class="form-control" name="' . $field['key'] . '">';
            foreach( $field['choices'] as $k => $v )
                echo '<option value="' . $k . '">' . $v . '</option>';
            echo '</select>';


The Codex includes a useful page on AJAX in plugins which outlines how to send and receive an ajax request.

The code below covers how you would trigger an event when the select field is changed and fire off the ajax request. Make sure you're getting and setting a nonce value.

* Only execute after jQuery is loaded
jQuery(document).ready(function ($) {

     * Trigger an event when the select field is changed.
    $( 'select[name="field_5481bc1472b1d"]' ).change( function() {

         * The data you will send via ajax. Action
         * needs to be a unique slug you will use
         * to identify and respond to the call.
         * An nonce will be needed to verify the
         * authenticity of the call.
        var data = {
            'action': 'customslug-action-name',
            'selected': $(this).val(),
            'nonce': YOUR_NONCE_VALUE,

        $.get( ajaxurl, data, function( r ) { 

            if ( r.success ) {
                // do your thing
            } else {
                // there was some error

Then on the server side, you would receive and respond to the call by hooking into the authenticated and unauthenticated ajax hooks associated with your action:

add_action( 'wp_ajax_customslug-action-name', 'my_action_callback_for_logged_in_users' );
add_action( 'wp_ajax_nopriv_customslug-action-name', 'my_action_callback_for_logged_out_users' );

Make sure you are using check_ajax_referrer() to verify the nonce. You can generate an nonce with wp_nonce_field() or pass it directly to JavaScript with wp_create_nonce.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.