Pass global variable data to localize_script

The issue you’re encountering is related to the execution order in WordPress. Global variables in WordPress are request-specific and are not preserved across different requests or different parts of a request unless they are included within the same scope.

The wp_enqueue_scripts action runs before the template file is executed, hence your $product_filter_data array is still empty when enqueue_scripts is executed.

Here are two potential solutions to the problem:

  1. Use WordPress Transients: WordPress Transients API can be used to store temporary data that can be retrieved later in the same or a subsequent request. Transients are essentially WordPress Options, but with expiration times.
// In your product-list-section.php
set_transient('product_filter_data', $product_filter_data, 12 * HOUR_IN_SECONDS);

// Then, in your setup.php file:
function enqueue_scripts() {
    $product_filter_data = get_transient('product_filter_data');
    wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array(), '1.0.0', true);
    wp_localize_script('custom-js', 'product_filter_data', array('php_product_filter_data' => $product_filter_data));
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

  1. Use wp_footer action: Instead of localizing the script at the time of enqueuing, you can do it at the time of wp_footer action, which occurs after the template file is processed.
// Then, in your setup.php file:
function enqueue_scripts() {
    wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

function localize_script_in_footer() {
    global $product_filter_data;
    wp_localize_script('custom-js', 'product_filter_data', array('php_product_filter_data' => $product_filter_data));
}
add_action('wp_footer', 'localize_script_in_footer');

Remember to replace custom-js with the handle of your actual script and replace product_filter_data with your data object name. And also, I haven’t tested this code. So you may need to do some changes to it so it works properly with your setup.

tech