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.

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.

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



Leave a Reply