Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enqueue WP Script that contained PHP variables

Tags:

php

wordpress

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' );
like image 802
DarkSpartan47 Avatar asked Mar 10 '23 05:03

DarkSpartan47


2 Answers

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.

like image 132
Vaibhav Rathore Avatar answered Mar 11 '23 17:03

Vaibhav Rathore


  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.
like image 35
Shahbaz Ahmed Avatar answered Mar 11 '23 17:03

Shahbaz Ahmed