How to pass dynamic values from PHP to CSS/JS in WordPress

There are situations when you have to use some values stored in DB or values being calculated in PHP script based upon different conditions in the java-script and css code. This can be achieved by writing the inline js/css code directly inside the php script. But in WordPress, this can be done very easily with help of functions built for that which is kind of more neat and clear way of doing the same.

Image: Flicker
Photo Credit: Dmitry

Pass dynamic values from PHP to JS in WordPress:

wp_localize_script( $handle, $name, $data ) : Makes any dynamic data available to your java-script that is available in the server side of WordPress.

/**
 * Load the front-end js scripts.
 */
function load_frontend_scripts() {
	wp_register_script( 'your_script_handle', get_bloginfo( 'template_url' ) . '/js/your_script_file.js' );
	wp_enqueue_script( 'your_script_handle' );
	wp_localize_script(
		'your_script_handle', 'ajaxobject',
		array(
			'ajaxurl'   => admin_url( 'admin-ajax.php' ),
			'ajaxnonce' => wp_create_nonce( 'your_unique_ajax_nonce' )
		)
	);
}
add_action( 'wp_enqueue_scripts', 'load_frontend_scripts' );

Now in the JS code the above passed values can be accessed as: ajaxobject.ajaxurl, ajaxobject.ajaxnonce

 

Pass dynamic values from PHP to CSS in WordPress:

wp_add_inline_style( $handle, $data ) : Adds in-line style with dynamic data being passed from php.

/**
 * Add background-image to hero area in the theme.
 */
function load_frontend_styles() {

	wp_register_style( 'your_theme_style_handle', get_bloginfo( 'template_url' ) . '/css/your_theme_style_file.css' );
	wp_enqueue_style( 'your_theme_style_handle' );

	$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'theme-hero' );
	$css = '.hero.with-featured-image { background-image: url(' . esc_url( $thumbnail[0] ) . '); }';

	wp_add_inline_style( 'your_theme_style_handle', $css );
}
add_action( 'wp_enqueue_scripts', 'load_frontend_styles' );

It will add inline css into the header of your page like the below.

<style id='your_theme_style_handle-inline-css' type='text/css'>
.hero.with-featured-image { background-image: url(http://test.local/wp401/wp-content/uploads/2015/01/46eccf2592_k-1230x820.jpg); }
</style>

 

References:
http://codex.wordpress.org/Function_Reference/wp_localize_script
http://codex.wordpress.org/Function_Reference/wp_add_inline_style


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *