This question already has answers here:
Wordpress how to use jquery and $ sign
(17 answers)
Closed 4 years ago.
I include some custom javascript into my wordpress theme. So I added this lines to my functions.php
function add_theme_scripts() {
wp_enqueue_script('equalheight', get_template_directory_uri().'/js/equalheight.js', array ( 'jquery' ), true);
wp_enqueue_script('script', get_template_directory_uri().'/js/script.js', array ( 'jquery' ), true);
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
But the scripts having problems with jquery. I will get this in my browser console:
TypeError: $ is undefined
Why? The dependence to jquery is set.
Does anyone have an idea?
If you will check for the declaration of wp_enqueue_script then its like that:-
wp_enqueue_script(
string $handle, string $src = '', array $deps = array(),
string|bool|null $ver = false, bool $in_footer = false
)
Its third parameter is used to define the dependency and in your code, you defined that these two files need jquery to work correctly.
If you don't need jquery, use this
function add_theme_scripts() {
wp_enqueue_script(
'equalheight',
get_template_directory_uri().'/js/equalheight.js',
array (), true
);
wp_enqueue_script(
'script',
get_template_directory_uri().'/js/script.js',
array (), true
);
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
You have dependency for jQuery set, but you have not loaded jQuery itself:
function add_theme_scripts() {
wp_enqueue_script("jquery");
wp_enqueue_script('equalheight', get_template_directory_uri().'/js/equalheight.js', array ( 'jquery' ), true);
wp_enqueue_script('script', get_template_directory_uri().'/js/script.js', array ( 'jquery' ), true);
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
Also as others have mentioned in the comments, you need to use jQuery-variable instead of $.
Related
I am trying to follow this tutorial on the WordPress Customizer JavaScript API, but I am running into the following snag:
When I try to run this code, I get the following error:
Uncaught TypeError: Cannot read property 'bind' of undefined
(function($){
var customize = wp.customize;
customize.previewer.bind( 'preview-edit', function( data ) {
// Some code
} );
})(jQuery);
I am enqueueing the script in my functions.php with the following hook:
function wf_customize_control_js() {
wp_enqueue_script( 'wf_customizer_control', get_template_directory_uri() . '/assets/js/wf-customize.js', array( 'customize-controls', 'jquery' ), null, true );
}
add_action( 'customize_controls_enqueue_scripts', 'wf_customize_control_js' );
Considering discussion on your question: wrap your function into jQuery(document).ready function to prevent your code running earlier than defined variable from other js script you're trying to use.
What would be the most appropriate solution to enqueue a script in WordPress only when a class of .google-map is detected on that page?
In my main.js I can detect the item on the page and do something, but I am not so sure you can use the enqueue function in a JS file.
$(document).ready(function(){
if (document.getElementsByClassName('.google-map')) {
alert(true);
}
});
The above is just attempt #1. Please feel free to provide any other solutions, using functions or anything else. I am simply not too sure what is possible that's why I don't have more examples.
Ordinarily add the file google.js (or whatever name you choose) to WP footer by adding the code below into your functions.php file. This will add the javascript file into WP footer the right way. https://developer.wordpress.org/reference/functions/wp_enqueue_script/
function my_scriptings_scripts() {
wp_enqueue_script( 'my_scriptings', get_template_directory_uri() . '/js/google.js', array('jquery'), '20171212', true );
}
add_action( 'wp_enqueue_scripts', 'my_scriptings_scripts' );
Inside your js/google.js
Using Vanilla javascript, check for the element with class name. If it exists then call the function for the action.
var element = document.getElementByClassName('google-map');
if (typeof(element) != 'undefined' && element != null)
{
//call function for google actions
google_acts_like_this();
}
function google_acts_like_this(){
console.log('Google will take over the world');
alert('Google will take over the world');
}
OR Try wienter code hereth Jquery -
if ($(document).find(.google-map).length > 0)
{
//If the element exist, then do something.
google_acts_like_this();
}
function google_acts_like_this(){
console.log('Google will take over the world');
alert('Google will take over the world');
}
I am trying to run a function on a specific WP page template. The specific page is called archive.php.
This is what I have so far in functions.php
if ( is_page_template( 'bloginfo("stylesheet_directory")/archive.php' ) ) {
function add_isotope() {
wp_register_script( 'isotope', get_template_directory_uri().'/js/isotope.pkgd.min.js', array('jquery'), true );
wp_register_script( 'isotope-init', get_template_directory_uri().'/js/isotope-hideall.js', array('jquery', 'isotope'), true );
wp_enqueue_script('isotope-init');
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
} else {
function add_isotope() {
wp_register_script( 'isotope', get_template_directory_uri().'/js/isotope.pkgd.min.js', array('jquery'), true );
wp_register_script( 'isotope-init', get_template_directory_uri().'/js/isotope.js', array('jquery', 'isotope'), true );
wp_enqueue_script('isotope-init');
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
}
The different between the functions is isotope-hideall, which hides all categories when the page is loaded. When not using if/else it hides all categories from all page templates when page is loaded, and that is not what I want. Therefor I am using if/else to locate the correct page template.
I have tried the following, but nothing seems to work:
is_page_template( 'archive.php' )
is_page_template( 'get_template_directory_uri()'.'/archive.php' )
Am I doing something wrong, or do you have a working solution for this?
Page can be found here.
As Pieter Goosen points out, archive.php is reserved for built in WordPress-functionality. Rename your file to something else, for instance to archives.php and make sure you are naming your custom page template at det top of the file:
<?php /* Template Name: Archives */ ?>
Your code should then work with is_page_template('archives.php') as longs as its located on root in your template folder. If not add whatever folder structure you have in front of the filename, like so: /folder/folder2/archives.php .
To avoid repeating the function twice you should also consider solving this something like so:
function add_isotope( $isotope ) {
wp_register_script( 'isotope', get_template_directory_uri().'/js/isotope.pkgd.min.js', array('jquery'), true );
wp_register_script( 'isotope-init', get_template_directory_uri().'/js/' . $isotope . '.js', array('jquery', 'isotope'), true );
wp_enqueue_script('isotope-init');
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
if ( is_page_template( 'archives.php' ) :
add_isotope( 'isotope-hideall' );
else :
add_isotope( 'isotope' );
endif;
Your complete logic is wrong here. Archives are targeted with is_archive() or the more specific conditional tag is_date() for normal archives. Note that is_archive() returns true on category, author, tag, date and taxonomy pages, so is_archive() might be a bit too generic to use if you only need to target archive
Also, your conditionals should be inside the function, not outside it as the conditional checks are way too late for the wp_enqueue_scripts hook.
Your code should be something like this
function add_isotope() {
if ( is_archive() ) { // Change as needed as I said
// Enqueue scripts for archive pages
} else {
// Enqueue scripts for all other pages
}
}
add_action( 'wp_enqueue_scripts', 'add_isotope' );
I am developing a simple Wordpress app but I am having an issue as all of the plugin scripts are rendered before those which are enqueued in my functions.php.
Here is a sample section of the functions.php:
function my_scripts() {
wp_register_script('app-js', get_template_directory_uri() . '/javascripts/app.js', array('jquery'), null, true );
wp_enqueue_script('app-js');
}
add_action( 'wp_enqueue_scripts', 'my_scripts');
The important this to note is that (following best practice my JS is set to render at the bottom of the page.
I also have couple of plugins running on the theme. The problem is that the output looks like this:
<!-- Note the plugin appears first -->
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/my-plugin/acl-plugin.js'></script>
<!-- And the main JS appears second -->
<script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/my-theme/javascripts/app.js'></script>
</body>
</html>
How can I force Wordpress to display the main JS (which i believe is rendered by wp_head() to appear at the very bottom of the page?
The WordPress wp_head() method will only output scripts or styles that have that last parameter in the WordPress wp_enqueue_script() set to false.. when it is set to true it will render in the footer via the wp_footer()
you can change the priority of when its called and inserted by adjusting the $priority parameter in the add_action()
http://codex.wordpress.org/Function_Reference/add_action
$priority
(int) (optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. Default: 10
add_action( $hook, $function_to_add, $priority, $accepted_args );
And also look at the following two WordPress methods:
wp_enqueue_script() :
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )
wp_register_script() :
https://developer.wordpress.org/reference/functions/wp_register_script/
wp_register_script( string $handle, string $src, array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )
Try this..
You might have to play with that $priority parameter
function my_scripts() {
wp_register_script('app-js', get_template_directory_uri() . '/javascripts/app.js', array('jquery'), null, true );
wp_enqueue_script('app-js');
}
add_action( 'wp_enqueue_scripts', 'my_scripts', 20, 1);
I am trying to disable the JavaScript when the user is using IE. Is there a way to accomplish this in template.php or a custom module?
As alternative to handling the content of $vars['scripts'], which is a string containing the HTML to output in the <head> tag, you could use the value returned from drupal_add_js(NULL, NULL, 'header'), which is similar to the following one:
$header_javascript = array(
'core' => array(
'misc/jquery.js' => array(
'cache' => TRUE,
'defer' => FALSE,
'preprocess' => TRUE,
),
'misc/drupal.js' => array(
'cache' => TRUE,
'defer' => FALSE,
'preprocess' => TRUE,
),
),
'module' => array(),
'theme' => array(),
'setting' => array(
array('basePath' => base_path()),
),
'inline' => array(),
);
The "module" index contains the reference to the JavaScript files added from the modules, "settings" contains all the JavaScript settings generally added by the modules, and "inline" contains inline JavaScript code.
It could help if you need to distinguish between the different JavaScript files, and (for example) not touch any JavaScript file that has been marked as "core."
The counterbalance is that to populate the content of $vars['scripts'] you need to duplicate part of the code used from drupal_get_js(). As you would need a customized code, you would not duplicate all the code of that function, but you still would duplicate part of it.
In Drupal 7, the variable $vars['scripts'] is not passed anymore to template_preprocess_page() (and similar preprocess functions implemented by modules or themes); it is passed to template_preprocess_html().
You can use the preprocess_page() hook in template.php.
function YOUR_THEME_preprocess_page(&$vars) {
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) {
$vars['scripts'] = 'get a mac!';
}
}
Obviously you should do something more intelligent with the $vars['scripts'] content :)