How can I use a theme option in a JS file? - javascript

I'm creating a Wordpress theme and have added an option which allowed users to change a font family using (simplified code): update_option('mytheme_font', $_POST['mytheme_font']);
How do I then get the value of that option in a JS file of the theme? I need it because I'm using Cufon to replace some H1's and H2's. Thanks!

You have four options I suppose.
Output your javascript to your page inside script tags. Easiest
<script>
<?php echo 'var x = 3;' ?>
</script>
Output the variable to your page and then read that from your javascript file. Clunky, but does mean you don't have to create some js globals.
<div id="x" style="display: none;">3</div>
var x = document.getElementById('x').innerHTML();
[Added] - Use AJAX to request the data and parse after page load.
Last and I don't recommend it, but setup php to parse .js files to dynamically produce javascript files. This way you could place a <?php ?> call in your .js files.

You could echo some thing like this in the <head> of the header.php
<?php
$defaultThemeFont = "myDefaultValue";
$userThemeFont = get_option("mytheme_font");
if($defaultThemeFont == NULL)
$userThemeFont = $defaultThemeFont
?>
<script>
<?php echo "var mytheme_font = $userThemeFont;"; ?>
</script>
Now you can access this variable from any JS file

Related

How to reuse same mixed code snippets by both PHP and JS? Best practice?

I'm just starting to learn JavaScript and PHP and am having troubles with this seemingly simple problem - how do I code reusable HTML snippets so they can be used both for JS and PHP?
Here's a case example - I have a simple .php page like this:
<body> <?php
foreach( $members_array as $member ) {
$id = $member->id;
$name = $member->name;
$img = $member->get_img();
include( 'single-member.php' );
}
foreach( $other_members_array as $member ) {
$id = $member->id;
$name = $member->name; ?>
<button type="button" onclick="addExtraMember" data-user-id="<?= $id? >">ADD <?= $name ?></button> <?php
}
</body>
Where for each member in the array a html code is dynamically generated with the variables. The 'single-member.php' is this:
<div id="<?= $id ?>">
<img src="<?= $img ?>">
<p><?= $name ?></p>
</div>
Then when the page finishes loading all the members are listed. The user of the page can click on one of the $other_members_array buttons that calls a JavaScript function. This JavaScript function should add the same code as 'single-member.php' after the last 'single-member.php' element to keep with visual consistency and in case I need to change the structure and styling of the snippet it's only in one file. I was googling this all afternoon today and here are my basic solutions:
rename the file to .html then load() and replace the attributes and text fields in JS
via .php page include one extra 'single-member.php' with empty values, a unique id and without displaying it so JS could grab it from the HTML DOM for re-use (in case the $members_array is empty)
don't load the members via PHP, add them all with JS when the page finishes loading using a reworked 'single-member.html' snippet without the PHP variables. So when a button is pressed JS function can use the 'single-member.html' again
I have a feeling this is a common problem - reusing elements and snippets between JS and PHP so I was wondering what the best practice is?
Also am I missing some more elegant library or solution?

WordPress - echo Advanced Custom Field in a .js file

I’m enqueue’ing scripts based on WordPress page template, and I need those scripts to be able to echo out ACF values. To make things more complicated, my script files dynamically build up HTML which includes custom fields e.g.:
innerHTML = '<img src="<?php echo the_field('ad_banner'); ?>"'
Is it possible to echo these fields in a .js file, to build up those HTML strings?
I've tried using wp_localize_script like below but am obviously doing something wrong:
wp_enqueue_script( 'pagination-retailers' );
wp_localize_script('pagination-retailers', 'script_vars', array(
'banner' => get_field("ad_banner")
)
);
Thanks very much
When you use wp_localize_script() its create you javascript object the name is the second argument in the function.
so you can call it in your javascript file like this
innerHTML = '<img src="'+script_vars.banner+'"';
you can also check the object in your page source code. it will be after the js file.

Passing variable from Php to js?

I am trying to send MY location to my js file. The location have the gives correct value when it is echoed from php. But when i try to access it from my js it does not access the correct value instead contains the value `<?php echo $location;?>` well how can i access the value in js?
PHP
while($loop->have_posts()):$loop->the_post();?>
<?php $location=get_field('location');?>
<div class="col-sm-15">
<div class="widget-box">
<div class="weather"></div>
</div>
</div>
<?php
endwhile;
locate must contain the value of location passed by php every tym the code loops` but why it is not actually passing any data?
jS file
var locate="<?php echo $location?;>";
alert (locate);
$(".weather").html(html);
The problem is you are saving the whole file in .js format where the php code you write is not parsed.
Instead you can do this just set the variable in the .php file where it can be excecuted like
PHP File
window.locate="<?php echo $location?;>";
and now use that variable in js file
alert (window.locate);
From js file one cannot access php variable.
You can do this from you php file and access locate in your js file
<script>
var locate = <?php echo $location ?>;
</script>

Pass XML configuration file to JavaScript via cached HTML

I need to pass data from an XML configuration file to JavaScript. The application needs to work entirely offline (I'll be using application cache and localstorage) and I was planning to generate the page using PHP. Is there an easy way to place the XML in the outputted document in such a way that it will not interfere with standard HTML parsing but still be easily accessible using JavaScript.
If, as suggested by the comments, you can use json instead, then you can set it to an html tags data attribute:
<?php $settings = array('name'=>'john');?>
<div id="mydiv" data-settings="<?php echo json_encode($settings); ?>"> <!-- --> </div>
Then retrieve it in javascript:
var mydiv=document.getElementById('mydiv');
var settings=JSON.parse(mydiv.dataset.settings);
alert(settings.name); //alerts john
or simply echo it into a script tag:
<script type="javascript">
var settings=<?php echo json_encode($settings); ?>;
</script>

how to insert array into javascript inside zend_form

i need to pass an array from my zend action to the view, possibly by using ajax, which is yet to be decided. in order to do that, i need to insert a script element and inside it define javascript variable, to which i will then pass my php array to, but i'm having trouble inserting script element into a zend_form. what is the easiest way to include this code into my phtml script:
<script type="text/javascript">
var obj = <?php echo json_encode($php_array); ?>;
</script>
You can use the view helper inlineScript() to pass java script to your view.
in your action $this->inlineScript()->setScript('java script here');
echo this out in your view <?php echo $this->inlineScript() ?>
you can also use the json() helper to pass json to the java script in your view.
RockyFord's solution is overly complex IMO. Just assign the PHP array to any view variable and add the code you posted (modified to use view variable) to the end of the view script - just after echoing the form.
//controller
$this->view->php_array = array(...);
//view
echo $this->form;
<script type="text/javascript">
var obj = <?php echo json_encode($this->php_array); ?>;
</script>
It will work as you expect.
Using JSON view helper is not ideal to use beacuse it modifies the headers and also disables layout by default. You can replace json_encode with Zend_Json::encode to make it work even without json_extension loaded in PHP.

Categories

Resources