php - How to dynamically generate JavaScript code in WordPress? -
i setting options panel in wordpress theme , have 1 option, "client_id". want use value , put javascript file. possible wordpress? have "compiler" can return values js files? or how can add js function wordpress theme via functions.php ?
currently using wp_enqueue of styles , scripts. can add js function enqueue ?
i use localization on themes @ php data in javascript. isn't hard, i'm being detailed below.
first, make sure using enqueue load javascript file want work in footer. if enqueues before footer, wont data because footer we're going make our data available javascript. call looks in functions.php. null , true arguments essential making work, more info in codex
//functions.php wp_enqueue_script('my_custom_javascript', get_template_directory_uri() . '/assets/js/scripts.js', array('jquery'), null, true);
then in template, create global php array variable @ top of code. needed, add indexes array containing meaningful name, , data want use in javascript later.
<?php // template file get_header(); $javascript_data = array(); //... throughout template ... $javascript_data['some_data'] = 'some value'; $javascript_data['more_data'] = $some_variable;
then, in footer, before call get_footer(), add localization function wraps php variable (containing you've added in template) in convenient javascript object. more more info in codex
<?php //footer.php wp_localize_script( 'my_custom_javascript', 'js_data', $javascript_data ); get_footer();
this take data have in php array, , localize my_custom_javascript script enqueue, making object can use in javascript file this:
// javascript file alert(js_data.some_data); // or console.log(js_data.more_data); // add top of js debugging console.dir(js_data);
so you, after doing above, functions.php might include:
$javascript_data['client_id'] = get_client_id(); function get_client_id(){ // $client_id = code id here // return $client_id }
and footer localize data script, , js_data.client_id available in javascript file.
Comments
Post a Comment