Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

php - Problem passing data from a shortcode to Javascript

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...