In wordpress to attach different js files - javascript

In WP 4.2 project I attach js files like:
add_action('wp_print_scripts', array(&$this, 'admin_load_scripts'));
...
function admin_load_scripts()
{
wp_register_script('BackendArtistsSongsJs', $this->plugin_url . 'js/backend-scripts.js');
...
But I want different pages to attach different js files.
I can do it in these ways:
In admin_load_scripts to parse parse $_SERVER and depending
on current url to attach js file I need.
In related php file
to include this file I need.
If there is a better way for this and which way do you prefer?

If you want to load a script on a particular page you can use
<?php if( is_page('<page-name>')) { ?>
// You import
<?php } ?>

You can check your page and add this script for js file add.
like if you want add js file in home page .
function admin_load_scripts()
{
<?php
if(is_page('home')) { ?>
wp_register_script('BackendArtistsSongsJs', $this->plugin_url . 'js/backend-scripts.js');
}elseif(is_page('second page name')){
//Add code for second js script file .
}
...

Related

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.

.load() function won't load javascript

When I use the function .load(), it will load the page that I want to load in the div that is selected.
But when I want to use JavaScript/jQuery that I already have coded in other files, it wont work anymore.
It does work when I just include ''; the page static in the div.
Does anyone have an idea why this works like this?
Static:
<div id="loginCont" class="modal-body">
<?php
include 'login.php';
?>
</div>
by Javascript/jQuery
$("#memberFalse").on("click", function() {
$('#loginCont').load("/213server/_inc/login.php");
});
A PHP include that starts with "/" refers to the root of the server, unless specified otherwise in your php.ini file. Your code:
<div id="loginCont" class="modal-body">
<?php
include 'login.php';
?>
</div>
fetches "login.php" from the folder where the current page is located. You can display that location with:
<?php echo __DIR__ ?>
Your jQuery load() method should fetch the page "login.php" from that location too. There is obviously a mistake in the following path:
$('#loginCont').load("/213server/_inc/login.php");
Remember that Javascript/jQuery CANNOT fetch files outside the web root, but PHP can. For example, if your login.php file is located at "/var/_inc/login.php" and your web root is at "/var/www/", jQuery will never have access to login.php. If your login.php file is located at "/var/www/myproject/_inc/login.php", then your load() function should fetch it like this:
$('#loginCont').load("/myproject/_inc/login.php");

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')));

Woocommerce All JS And Jquery elements are not loading

I had made my theme to be compatible with woocommerce, by creating woocommerce.php, and adding a custom function in my functions.php file which is
add_theme_support( 'woocommerce' );
And this is how my woocommerce.php file looks like :
<?php
global $mandigo_options, $dirs;
get_header();
// heading level for page title (h1, h2, div, ...)
$tag_post_title_single = $mandigo_options['heading_level_post_title_single'];
?>
<td id="content" class="<?php echo ($mandigo_options['sidebar_always_show'] ? 'narrow' : 'wide'); ?>column"<?php if (mandigo_sidebox_conditions($single = true)) { ?> rowspan="2"<?php } ?>>
<div class="woocommerce">
<?php woocommerce_content(); ?>
</div>
</td>
<?php
// if we have at least one sidebar to display
if ($mandigo_options['sidebar_always_show'] && $mandigo_options['sidebar_count']) {
if (mandigo_sidebox_conditions($single = true))
include (TEMPLATEPATH . '/sidebox.php');
include (TEMPLATEPATH . '/sidebar.php');
// if this is a 3-column layout
if ($mandigo_options['layout_width'] == 1024 && $mandigo_options['sidebar_count'] == 2)
include (TEMPLATEPATH . '/sidebar2.php');
}
get_footer();
?>
Everything is appearing fine now, but I can't find the add to cart button and also all the elements that uses javascript or jquery are not loading.
I had tried :
To use wordpress JQuery updater
To put the jquery library reference in the header.php
Deactivating all plugins
I had all the fields of the necessary elements in woocommerce field like the price, but its obvious that this is a JS or JQuery error.
And here is a link to the site is product page :
http://www.doctor-detail.com/product/gift-card-product-2
Any help would be much appreciated!
When I inspected the site and checked the console I found that although I was linking to the latest jquery in the header of my site, it was using the main jquery of the theme.
So, all I needed to do is to remove the theme is Jquery file from the JS folder.
After that woocommerce was working fine.
You should use wp_enqueue_script() in functions.php instead of linking in a header.php, Plese keep in mind JQuery in enqueued by default. If you need to change version, fist you have to deregister the default one.

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

Categories

Resources