0

I have a wp_register_script / wp_enqueue_script and need to reuse this for multiple states, how do I do this?

This is the code:

  wp_register_script( 'scount', get_template_directory_uri() . '/assets/js/us-states.js' );

  // Localize the script with our data that we want to use
  $args = array(
    'post_type' => 'property',
    'fields' => 'ids',
    'meta_query' => array(
    'relation' => 'AND',
     array(
         'key' => 'state',
         'value' => 'NC'
         ),
     array(
         'key' => 'available',
         'compare' => '=',
         'value' => '1'
     )
     )
  );
  $results = new WP_Query($args);
  $completed = count($results->posts);
  wp_localize_script( 'scount', 'completed', $completed );

  // The script can be enqueued now or later.
  wp_enqueue_script( 'scount' );

So I need to use this for every state in the usa. The one I have is for NC only. I tried to duplicate and change to another state, and it works but it adds the us-states.js file twice, so If I did this for every state I would have the us-states.js file added 50 times!!

I need to use the completed for adding the results into a the json file: ( JSON.stringify(completed) )

and I would need for each state.

Thank you!!

  • 1
    Welcome to WPSE. You will need to identify a condition which will determine what to localize the script with and then only one instance will be loaded. Is there a page template, query variable or some other data point you can test for? – jdm2112 Aug 30 '18 at 19:34
  • I just saw your earlier question and that may answer my comment above. Reviewing now... – jdm2112 Aug 30 '18 at 19:36
  • I am using the results of this to add to json file: ( JSON.stringify(completed) ) – Melinda Aug 30 '18 at 19:38
1

If I understood you correctly you have to give your code a bit of refactoring and call wp_localize_script strategically.

Based on your code, I'd say you have two options.

  1. You can call wp_localize_script once, add as many values as you want within $l10n array and create only one $object_name to be used within JS.
  2. You can call wp_localize_script as many times as you need, but your $object_name needs to be unique for each time you call it.

Please pay attention to the code, especially the comments:

function register_scount_script() {
    // As a best practice use `get_stylesheet_directory_uri` instead of `get_template_directory_uri`, unless you really know what you are doing.
    wp_register_script( 'scount', get_stylesheet_directory_uri() . '/assets/js/us-states.js', array( 'jquery' ), '1.0.0', true );
}

/**
 * First method. You will call `wp_localize_script` once, add as many values as you want within $l10n array
 * and create only one $object_name to be used within JS.
 */
function localize_scount_script_first_method() {
    $args = array(
        'post_type'  => 'property',
        'fields'     => 'ids',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'   => 'state',
                'value' => 'NC'
            ),
            array(
                'key'     => 'available',
                'compare' => '=',
                'value'   => '1'
            )
        )
    );

    $results      = new WP_Query( $args );
    $nc_completed = count( $results->posts );

    // At this point, you can execute the query again and just change 'state' key value to 'SC', for instance.
    // Then you would have/create a new variable $sc_completed.

    /**
     * @param string $handle Script handle the data will be attached to.
     * @param string $object_name Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
     * @param array $l10n The data itself. The data can be either a single or multi-dimensional array.
     */
    wp_localize_script(
        'scount',
        'completed',
        array(
            'nc_completed' => $nc_completed, // This value would be accessible in JS using var completed.nc_completed
//          'sc_completed' => $sc_completed // This value would be accessible in JS using var completed.sc_completed
        )
    );

    // Make sure you reset $wp_query global. If not you might have trouble somewhere else in your code.
    wp_reset_query();
}

/**
 * Second method. You will call `wp_localize_script` as many times as you need, but your $object_name needs to be unique
 * for each time you call it.
 */
function localize_scount_script_sec_method() {
    $args = array(
        'post_type'  => 'property',
        'fields'     => 'ids',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'   => 'state',
                'value' => 'NC'
            ),
            array(
                'key'     => 'available',
                'compare' => '=',
                'value'   => '1'
            )
        )
    );

    $results   = new WP_Query( $args );
    $completed = count( $results->posts );

    /**
     * @param string $handle Script handle the data will be attached to.
     * @param string $object_name Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
     * @param array $l10n The data itself. The data can be either a single or multi-dimensional array.
     */
    wp_localize_script(
        'scount',
        'nc_completed', // Needs to be unique!
        array(
            'completed' => $completed, // This value would be accessible in JS using var nc_completed.completed
        )
    );

    // At this point you could perform a new query and localize again:
    $args = array(
        'post_type'  => 'property',
        'fields'     => 'ids',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key'   => 'state',
                'value' => 'SC' // Changed to SC.
            ),
            array(
                'key'     => 'available',
                'compare' => '=',
                'value'   => '1'
            )
        )
    );

    $results   = new WP_Query( $args );
    $completed = count( $results->posts );

    /**
     * @param string $handle Script handle the data will be attached to.
     * @param string $object_name Name for the JavaScript object. Passed directly, so it should be qualified JS variable.
     * @param array $l10n The data itself. The data can be either a single or multi-dimensional array.
     */
    wp_localize_script(
        'scount',
        'sc_completed', // Needs to be unique!
        array(
            'completed' => $completed, // This value would be accessible in JS using var sc_completed.completed
        )
    );

    // Make sure you reset $wp_query global. If not you might have trouble somewhere else in your code.
    wp_reset_query();
}

function enqueue_scount_script() {
    wp_enqueue_script( 'scount' );
}

add_action( 'wp_enqueue_scripts', 'register_scount_script' );
add_action( 'wp_enqueue_scripts', 'localize_scount_script_first_method', 11 );
//add_action( 'wp_enqueue_scripts', 'localize_scount_script_sec_method', 11 );
add_action( 'wp_enqueue_scripts', 'enqueue_scount_script', 12 );

Make sure you always enqueue/register/localize scripts making use of wp_enqueue_scripts action hook.

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.