WordPress Options Passed To JavaScript #1

In WordPress you are not always in the PHP world and so you have to pass settings and data from the database to scripts sometimes. In many Plugins you can find solutions in loading the wp-load.php and therefore access to all features of WordPress. Long ago Otto (Samuel Wood) already referred to this fact and this articles shows solutions. Questions still there and still there are Plugins that load the wp-load.php precisely because of such problems.

A similar problem arises when the source of the scripts is not just written in the footer area of WordPress, but outsourced to a file and via wp_enqueue_script() included. Only then WordPress can manage, compromises and optimizes these scripts for delivery. Therefore I would like to show two examples, how to pass data from PHP to JS.

The first snippet uses the pass of values ​​via JSON to get the values ​​from the database with the current resources in PHP and the script stores directly in the header of the page the values ​​as an object.

add_action( 'admin_enqueue_scripts', 'fb_print_scripts' );

function fb_print_scripts() {
	global $current_screen;
	
	if ( isset( $current_screen -> id ) && ! in_array( $current_screen -> id, array( 'post', 'page' ) ) )
		return;
	
	if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) )
		$options = get_site_option( 'my_options_id' );
	else
		$options = get_option( 'my_options_id' );
	
	if ( ! $options )
		return;
	?>
	<script type="text/javascript">
		var my_json_object = <?php echo json_encode( $options ); ?>;
	</script>
	<?php
}

The above function gives the values ​​from the database as a JSON object in the head of the backend, as the page was requested in the first step of the function. Via $current_screen it will be checked so it will be only delivered if you are on one of the defined pages (post, page).

The next step is common practice and best solution to include scripts in WordPress. Thereby I will include the JS file, which then has accesses to the JSON object.

add_action( 'admin_enqueue_scripts', 'fb_admin_enqueue_scripts' );

function fb_admin_enqueue_scripts( $where ) {
	
	if ( ! in_array( $where, array( 'post.php', 'post-new.php', ) )
		return;
	
	$suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '.dev' : '';
	
	wp_enqueue_script(
		self :: get_textdomain() . '_script', 
		plugins_url( '/js/my_script' . $suffix. '.js', __FILE__ ), 	
		array( 'jquery', 'my_other_script' ),
		'',
		TRUE
	);
	
}

The script accesses directly the object that is processed.

jQuery( document ).ready( function( $ ) {
	
	if ( typeof my_json_object == 'undefined' )
		return;

// debug in console of Browser
console.dir( my_json_object ); 

});

Another solution will be presented in the following post at this series.

Comments are closed.

16 comments

  1. Sergey Vlasov

    You could go further another step and use wp_localize_script subsequently with admin_enque_script to avoid mixing PHP and JavaScript code.

  2. Rilwis

    Why don't you use wp_localize_script? It can be used to pass PHP variables to JS.

  3. Saroj

    it can be done easily with wp_localize_script()

  4. Patrik

    Isn't http://codex.wordpress.org/Function_Reference/wp_localize_script an better way to include custom options?

  5. Frank

    @Saroj, @Patrik: please wait for part #2 of this posts, i will clarify this function and also the problems, there you can have with wp_localize_script(). Thanks for your comments.

  6. Patrik

    Looking forward to the next to see what problems may occur

  7. adumpaul

    Nice article.Excellent javascript code is used.Thank you for sharing.

  8. jason

    console.log('thank you');

    Very nice post.

  9. Genevieve Windsor

    wp_localize_script() is important to use after it has been enqueued. These codes are really helpful. I almost know nothing in java script since I often code using php. I'll keep visiting for more of your posts.

  10. sintu kumar

    great article....i think it can also be done easily using wp_localize_script()...thanks for sharing

6 pingbacks

  1. WordPress Options Passed To JavaScript #1 – WP Engineer | Casapress.info
  2. WordPress Options Passed To JavaScript #1 - WPengineer.com | Jerry DeFoe
  3. WordPress Options Passed To JavaScript #1 | Wordpress news and updates
  4. WordPress Options Passed To JavaScript #1 | WPhub.biz
  5. L’Hebdo WordPress : Mobiles – WordPress 3.4 – Astuces
  6. WordPress Options Passed To JavaScript #2 » Planet WordPress