简体   繁体   English

如何使用wp_localize_script将php变量传递到Wordpress中的* .js文件

[英]How to pass php variables to a *.js-file inside Wordpress with wp_localize_script

I am working on a WordPress plugin, that uses data from the backend to display it in the frontend. 我正在研究一个WordPress插件,该插件使用来自后端的数据将其显示在前端。

I've got two important files. 我有两个重要文件。 One PHP plugin file with a form, where users can submit data and one JavaScript file of another Plugin, where the data should be implemented into a dynamically generated content file. 一个具有形式的PHP插件文件,用户可以在其中提交数据,而在另一个PHP插件中,一个JavaScript文件可以在其中将数据实现为动态生成的内容文件。

First, I used an iframe to implement the data, which is stored in an HTML file, but this method has many disadvantages. 首先,我使用iframe来实现存储在HTML文件中的数据,但是这种方法有很多缺点。 I would like to insert the data directly with a string-variable passed from the PHP file to the JavaScript file and figured out, that wp-localize-script should do that, but I cant get it to work. 我想直接使用从PHP文件传递到JavaScript文件的字符串变量插入数据,并弄清楚wp-localize-script应该可以执行此操作,但是我无法使其正常工作。

In my PHP plugin file, my code looks like this: 在我的PHP插件文件中,我的代码如下所示:

$phptestvariable = "Ausgabe der PHP-Testvariable";

function js_enqueue_scripts() {

    wp_register_script("scripts", plugin_dir_url(__FILE__) . '/wp-content/plugins/h5p/h5p-php-library/js/h5p.js' );
    wp_enqueue_script("scripts");
    wp_localize_script("scripts", "php_vars", $phptestvariable);
}
add_action("wp_enqueue_scripts", "js_enqueue_scripts");

In my JavaScript file (/wp-content/plugins/h5p/h5p-php-library/js/h5p.js) the code looks like this: 在我的JavaScript文件(/wp-content/plugins/h5p/h5p-php-library/js/h5p.js)中,代码如下所示:

actionBar.on('cc', function () {

    console.log(php_vars.variable);
    var dialog = new H5P.Dialog('copyrights', H5P.t('ccInfo'), php_vars , $container);
        // Übergabe Werte: Button Name, PopUp Titel, PopUp Inhalt, $container
    dialog.open();
    instance.triggerXAPI('accessed-copyright');
});

How can I fix this? 我怎样才能解决这个问题?

3rd parameter of wp_localize_script has to be an array. wp_localize_script第三个参数必须是一个数组。 For example: 例如:

wp_localize_script( 'scripts', 'php_vars',
    array( 
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'var_1' => 'Ausgabe der PHP-Testvariable'
    )
);

Then somewhere in your JS 然后在您的JS中

alert(php_vars.var_1)

will display value 1 将显示value 1

PS ajax_url contains and URL to make your AJAX calls in case you need that too. PS ajax_url包含和URL,以在需要时进行AJAX调用。 Here is some explanation on that. 是一些解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM