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 have a slider in my theme. I have a setting in the options which controls whether that slider is set to "slide" or "fade". This slide/fade setting is in the jquery and of course the options setting is in the database. I presume the normal method of getting this setting is via AJAX but I thought I'd ask as I have a number of other similar scenarios on this theme.

I always think of AJAX as meaning "change data without having to re-load the page" .... but in this case I just want jquery to have access the data when the page is first loaded ... so it seems my "understanding" is a bit off and jquery is needed for any time javascript/jquery needs to get info from the database.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Enqueue the script as you would normally, & then call the JS function right after the slider HTML output (or on wp_footer), and pass a JSON config back to the function.

<!-- slider HTML -->
<script type="text/javascript">
    jQuery( "#my_slide" ).mySlider(
        <?php echo json_encode( $my_config /* array or object of arguments */ ) ?>
    );
</script>

Alternatively, enter wp_localize_script:

wp_enqueue_script( 'my-slider', plugins_url( 'js/slider.js', __FILE__ ), array( 'jquery' ) );
wp_localize_script( 'my-slider', 'My_Slider', array(
    'somevar' => get_option( 'my_var' ),
));

This'll output in the head something like:

<script type="text/javascript">My_Slider = { "somevar": "value of get_option( 'my_var' )" }</script>
<script type="text/javascript" src="http://example.com/wp-content/plugins/my-slider/js/slider.js"></script>

See how you now have access to the JS global My_Slider?

share|improve this answer

You need to use wp_localize_script to pass PHP variables to your javascript.

In your javascript file you can reference the variable as such:

myCustomVariable.fadeOption

Then in your options panel you can assign $_POST['fade_option'] to myCustomVariable.fadeOption:

function load_fade_option(){
  wp_enqueue_script('slider', 'slider.js', array( 'jquery' ));
  wp_localize_script('slider', 'myCustomVariable',
    array(
            'fadeOption' => $_POST['fade_option'],
         )
    );
}

Pippin has some good documentation on this:

http://pippinsplugins.com/use-wp_localize_script-it-is-awesome/

share|improve this answer

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.