Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Enqueue WP Script that contained PHP variables

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' );
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

  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.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!