What is the “proper” way to generate a javascript variable depending on a custom field value?

You may wish to look at this question. In that question, the admin-ajax url is passed through, but it can be any variable (or array of variables), like for instance $nameAttribute. For instance, you would call wp_localize_script(‘my_js_file_handle’,’my_js_object’,array(‘attribute’=>$nameAttribute))` then in your js file, the variable would be accessible from my_js_object.attribute. (You must enqueue the javascript file … Read more

Pass data from wordpress to javascript in JSON

Try wrapping your array in json_encode(): function add_map_data() { $objName = “MapData”; $array = array( “MapViewLatitude” => “51.505”, “MapViewLongitude” => “-0.09”, ); wp_enqueue_script( ‘mapdata’, get_bloginfo(‘template_url’).’/custom/map.js’, null, null, false ); wp_localize_script( ‘mapdata’, $objName, array(‘my_arr’ =>json_encode($array))); } add_action( ‘wp_enqueue_scripts’, ‘add_map_data’); Next step is to parse the JSON string back to a JSON object in JavaScript so: //first … Read more

JavaScript && operator in visual editor

You should use wp_enqueue_script for your javascript files instead of adding the code directly into the post content. ps: You can check out the callbacks on the the_content filter, using add_action(‘wp_footer’,function(){ global $wp_filter; printf(‘<pre>%s</pre>’,print_r( $wp_filter[‘the_content’],true)); }); to display them in the footer part of your theme. Then you will see callbacks like wpautop, wptexturize, convert_chars … Read more

Best approach to fetch data from wp options to js file or php file

Assuming you’re not using AJAX for form submission, you can use wp_localize_script(). Here’s a simplified version: In your plugin file: function wpse105919_add_scripts(){ wp_enqueue_script( ‘myjs’, plugins_url( ‘/myjs.js’, __FILE__ ) ); wp_localize_script( ‘myjs’, ‘jsLocalizedObject’, ‘hello world’); } add_action(‘wp_enqueue_scripts’, ‘wpse105919_add_scripts’); contents of myjs.js file: alert( jsLocalizedObject ); wp_localize_script() will add a global variable called jsLocalizedObject to your document’s … Read more

Dealing with a library that depends on jQuery

First of all if you investigate PikaChoose source code, then you will see that it wraps the code with self invoking closure: (function($) { // … })(jQuery); It means that they use short form properly. In the same time it means that all you need to do is to enqueue jQuery and PikaChoose scripts and … Read more