排队包含PHP变量的WP脚本

I am trying to find out if you can enqueue a script in Wordpress that has php variables within it. If this is possible how would it be done?

I have tried this, however I get errors.

function my_scripts_method() {
wp_enqueue_script(
    'custom-script',
    get_stylesheet_directory_uri() . '/masonry.php',
    array( 'jquery' )
);
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
  1. In your php file called masonry.php

<?php header('Content-type: application/javascript'); $php = 'Hello World'; echo "alert('$php');";

And then link/enqueue your php as if it was a javascript file:

wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/masonry.php', array( 'jquery' ) );

  1. You can use wp_add_inline_script function to print the inline code.

Your question is a bit ambiguous.

  1. If you want to include a PHP file, use include_once or require_once in your PHP file.
  2. If you want to include JavaScript file, use wp_enqueue_script. Your code should be something like:

    wp_enqueue_script(
        'custom-script',
        get_stylesheet_directory_uri() . '/masonry.js',
        array( 'jquery' )
    );
    

    Moreover, if you want to use PHP variables inside a JS file, use wp_localize_script.

    After enqueue, use the following line:

    $name = "my_name";
    $params = array('name' => $name);
    wp_localize_script( 'custom-script', 'OBJECT', $params );
    

    Inside your masonry.js, use OBJECT.name to get the value.