I have a problem when passing attributes from a shortcode to JavaScript to make a query on Firebase.
From the shortcode to the array the data is fine, but when passing it to Javascript it passes the data by default.
Shortcode:
[custom_firebase clientid="0002" name="Louise"]
The function:
function custom_firebase_scripts_function($atts){
wp_enqueue_script('custom_firebase', get_template_directory_uri() . '/js/firebase-script.js',
array('firebase_app', 'firebase_auth', 'firebase_database', 'firebase_firestore', 'firebase'));
$atts = shortcode_atts(array(
'clientid' => '0001',
'name' => 'Matt PHP'
), $atts);
$paramsc = array (
'clientid' => $atts['clientid'],
'name' => $atts['name']
);
wp_add_inline_script('custom_firebase',' const vars_client = ' . json_encode($paramsc), 'before');
return '<div id="custom-firebase"> ' . $paramsc['clientid'] . ' </div>';//The result I get from this line is 0002.
}
add_shortcode('custom_firebase', 'custom_firebase_scripts_function');
add_action('wp_enqueue_scripts', 'custom_firebase_scripts_function');
I tried using wp_localize_script, but saw that the correct way is to use wp_add_inline_script, I got the same results anyway.
For the query in Firebase I refer to the attributes in this way, it shows the fields correctly, but not the documents I want.
const collectionName = 'Clients';
const documentName = vars_client.clientid;
console.log('Value: ', vars_client.clientid);
console.log('Value: ', vars_client.name);
The console shows the default values: 0001 and Matt PHP, but on the page it shows me 0002 (which is what I have as data in the shortcode).
Extra data that could be relevant:
- For the Firebase integration I use the Integrate Firebase plugin.
- I use Cloud Firestore.
- The php function is in function.php directly in the theme.
I have almost no knowledge of PHP, Javascript and HTML, there are probably things misspelled or with little logical sense, I apologize for that.
I am on the lookout for any extra information that is required.
Thanks.
question from:
https://stackoverflow.com/questions/65901797/problem-passing-data-from-a-shortcode-to-javascript