You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在jQuery中获取PHP变量值?(独立JS文件场景)

Can I pass a PHP variable to an enqueued standalone jQuery file?

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() after wp_enqueue_script()—it won’t work if you do it before.
  • Adding a fallback value (like 0 in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:35:33