Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am loading some jquery on a specific Wordpress admin page, the jquery loads and works fine but I need have this jquery only trigger if a php variable exists.

In php I would just write a function and hook it into the admin page:

I am enqueuing the jquery file, i.e., foo.js that contains this following jquery:

jQuery(document).ready(function($){
    $('#someID.some-class > a').append('<div class="caption"></div>');
    $(".caption").text("Add this text");
});

So the file foo.js file loads whenever the themes.php file is loaded but I do not want the jquery to run unless a variable is set by the themes.php page.

I am confused as to where and how I do check the variable and trigger the jquery.

Do I just add the jquery by echoing out the the jquery from within a function?

Do I somehow add the php variable check into the foo.js file?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Do I just add the jquery by echoing out the the jquery from within a function?

Do I somehow add the php variable check into the foo.js file?

No, off course no.

Use wp_localize_script. The original aim of this function was to translate the js scripts, but it allows to pass any kind of variables to js.

function register_foo() {
  wp_register_script('foo-js', plugins_url('js/foo.js', __FILE__), array('jquery'), null);
  $mydata = array(
    'foo' => 'bar', 'awesome' => 'yes'
  );
  wp_localize_script('foo-js', 'mydata', $mydata); // this one do the magic
  wp_enqueue_script('foo-js');
}
add_action('admin_enqueue_scripts', 'register_foo');

With this snippet the file 'foo.js' is inserted in admin pages, and a variable, that is a json object, is passed to the script and you can use it as you want.

Now, as example, in your 'foo.js' you can have;

jQuery(document).ready(function($){
    var foo = mydata.foo;
    var awesome = mydata.awesome;
    if ( foo == 'bar' ) {
      $('#someID.some-class > a').append('<div class="caption"></div>');
      $(".caption").text("Is this script awesome? " + awesome + '!');
    }
});
share|improve this answer
    
that is just the solution I was looking for thanks. –  Jason Aug 2 '13 at 2:27
    
thanks again, that worked perfectly and was the best solution anyone offered. –  Jason Aug 2 '13 at 5:14
    
You are welcome. This is the only 'official' solution. There are some tricks, but... –  G. M. Aug 2 '13 at 9:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.