能否在jQuery中获取PHP变量值?(独立JS文件场景)
Absolutely, this is totally feasible! You just can’t directly embed PHP code into your independent JS file (since PHP runs server-side and JS runs client-side). Instead, WordPress provides a built-in way to pass server-side data to client-side scripts using script localization. Here’s how to do it step by step:
Step 1: Localize your script in PHP
First, make sure you’re enqueuing your JS file correctly, then use wp_localize_script() to send the video length data to your JS file. This function creates a global JavaScript object that your script can access.
Here’s the updated PHP code:
// Enqueue your standalone JS file (adjust the path and handle to match your setup) wp_enqueue_script( 'custom-video-script', get_template_directory_uri() . '/js/your-script.js', array('jquery'), // Depend on jQuery since you're using it '1.0', true // Load in the footer for better performance ); // Your existing code to get the video metadata $attachment_id = attachment_url_to_postid( $_POST['background-video'] ); $video_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true ); // Safely get the video length (add a fallback in case the meta is missing) $video_length = isset( $video_meta['length'] ) ? $video_meta['length'] : 0; // Pass the PHP variable to your JS file wp_localize_script( 'custom-video-script', // Must match the handle used in wp_enqueue_script 'VideoSettings', // This will be the global JS object name array( 'videoDuration' => $video_length // The key/value pair your JS will use ) );
Step 2: Use the variable in your JS file
Now, in your enqueued .js file, you can access the video length via the global VideoSettings object. Replace your placeholder with this:
jQuery('input[name=slide_duration]').val(VideoSettings.videoDuration);
Important Notes:
- Always call
wp_localize_script()afterwp_enqueue_script()—it won’t work if you do it before. - Adding a fallback value (like
0in the example) prevents JavaScript errors if the video metadata is missing or invalid. - Choose a unique name for your global object (like
VideoSettings) to avoid conflicts with other plugins or themes.
This is the standard, recommended way to pass server-side data to client-side scripts in WordPress, and it works perfectly for your use case.
内容的提问来源于stack exchange,提问作者jockebq

