WordPress - echo Advanced Custom Field in a .js file - javascript

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.

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?

How to put php content into javascript markup?

I have a video gallery, and all the titles are generated by php. The lightbox for these videos, however, is customized in javascript. How can I put the php titles inside the iframe markup?
See here:
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> <?php the_title();?> </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
EDIT
For reference, I need the attachment title below ($attachment_data['title']) in the javascript section mentioned (the markup).
<?php
$the_query = new WP_Query(array(
'post_type' => 'attachment',
'category_name' => 'video'
));
while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<?php
$attachment_data = wp_prepare_attachment_for_js( $attachment->ID );
echo'<figure><a class="video" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
echo''.the_post_thumbnail ('medium').'';
echo'<div class="photo-title"><h2>'.$attachment_data['title'].'</h2></div></a></figure>';?>
<?php
endwhile;
wp_reset_postdata();
?>
Try this:
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> <?=the_title()?> </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
Notice the use of the <?= shorthand for echo. (read more about it)
There are a few ways to get javascript and PHP to interact. You could pull from the client using an ajax call. If you need to get a bunch of data asynchronously, that might be the thing. If you're going to have 20 copies of this iframe, you might consider using an AJAX call to pull a whole array of values/objects with JSON and then you can do with them whatever you'd like.
But... I suspect that you'll just use this iframe once per page. Rigging up some ajax for a once-per-page thing is probably a little overkill.
If you are putting your javascript right on your page, you could do as IzzEps suggested and simply echo your php values right into the iFrame. But I know most folks like to keep their javascript separate from their html content in a .js file. This makes it more maintainable. While not impossible, php most easily puts content onto .php files rather than others like js. I don't have any experience with getting a browser to use a php file for a script source.
What I've found easiest and cleanest is to write my javascript in my .js file as normal, then I'll add the variable(s) to my .php file as minimally as possible at the top in a script tag.
So, at the top of your page, you could do something like any of these:
<script>
ObjectYoureWorkingWith.Title = '<?php echo $the_title(); ?>';
var TitleObjectList = <?php echo json_encode($list_of_titles); ?>;
</script>
Basically, you feed input from your php into whatever module, object, array, or variable you're working with and then you can refer to that in your javascript wherever you need it. That way you're not forced into putting all your javascript right in with your html. You can even do this with a whole object or collection of object using json_encode (which is javascript's native object notation anyway).
Update:
I was typing the above on my cell (not the best way to respond to this sort of thing). Let me demonstrate what I'm describing:
Let's say in your php you have 20 titles you want to work with. You could make an associative array. Use an Id or whatever identifier you want to call it with.
$titleArray = [ 123 => 'Title1', 456 => 'Title2']; //(and so on....)
Then, on the php page you're wanting that data, do this:
<script>
var titleArray = <?php echo json_encode($titleArray); ?>;
</script>
This will now allow you to access it on that page (or in a js file loaded on that page) by doing this:
var myFirstTitle = titleArray["123"]; //This will return "Title1"
json_encode will take a PHP object and translate the public variables into a javascript object. Simply echoing this to a javascript variable will give javascript the object to work with.
The developer of the lightbox has a solution that I was already partly implementing. For the title to appear in the lightbox, I needed this callback from my original code:
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
But I had neglected to include the title in my PHP loop, corrected here:
echo'<figure><a class="video" title="'.$attachment_data['title'].'" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
There's a similar post that also covers this answer, for reference:
Title for iframe/video in magnific popup
Thanks again for all your help!

Insert javascript string into HTML with PHP in WP

I need to create some widget for WP and in widget's setting will be textarea, where user can insert some JS code. And then my widget must inject this code to WP's footer.php with this function:
add_action( 'wp_footer', 'inject_js', 10 );
In my inject_js I have:
function inject_js () {
echo esc_attr( get_option('js_code') );
}
Everything is working good and the code inserts into HTML, but I faced one problem. In my HTML I get something like this:
<!-- BEGIN JS widget -->
<script type="text/javascript">
var __cp = {
id: "J4FGckYPdasda21OaTnqo6s7kMgeGXdTBAb6SgXMD-A"
};
As I understand I got the code from user's textarea in string type and I must do something with the quotes and other symbols, but I really don't know how to solve this issue, because I am new to PHP.
What PHP function must I use or it's possible to do with some WP functions?
I tried:
echo htmlspecialchars(esc_attr( get_option('js_code') ));
and
echo addslashes(esc_attr( get_option('js_code') ));
But nothing helped.
You are seeing the effect of esc_attr - the function is html encoding (amoungst other things) the string.
It is designed for untrusted user input. As your code is specifically designed to accept javascript from a trusted source (the site owner), dont use it.
echo get_option('js_code');
wrap your code in this :- like this:
html_entity_decode(esc_attr( get_option('js_code')));

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

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

Kohana 3 JavaScript issue

We have a simple JQuery date picker that we are trying to include on a page. The function works on a strait html site, however, when we include the working function via Kohana the function does not work. We have tried including it both as a file by loading all of the JavaScript references in an array in a template and printing them with
<?php foreach($scripts as $file) { echo HTML::script($file, NULL, TRUE), "\n"; }?>
As well as simply putting the script in a separate view and using view::factory to include the file. When we do the latter the </script> tag is not recognized by browsers or at least its syntax highlighting is not picking it up, though this does not effect other scripts such as Google maps. For what ever it is worth, here is the function:
jQuery(function(){
jQuery(".datepick").datepicker();
});
and the element it is acting on is:
<input class="datepick" id="to" type="text" />
Does anyone have any suggestions for us. We are getting pretty desperate to make this one little simple function work.
You probably don't need the last TRUE on the HTML::script() call, as that will add index.php to your script URL, implying that you are using PHP to serve the actual script files.
In this case, I think your call should just be:
<?php foreach ($scripts as $file) { echo HTML::script($file), "\n"; } ?>
I don't think this is related to Kohana but to your HTML code.
How do you include your scripts (is jQuery included before your javascript code) ?

Categories

Resources