Running a javascript on a specific page - javascript

For some reason a js isn't running on a page on my wordpress development site called 'information'. The page template was copied from a page which successfully runs the script so I'm not sure what's missing. I've tried to remedy the situation by running this script in the functions.php file:
function my_scripts() {
if( is_page( array( 'information') ) ){
wp_enqueue_script( 'variable_fonts', 'js/variable_fonts.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
I've also tried running this script on the page itself:
<script>
if(location.pathname=="/information/")
script.src = /js/variable_fonts.js;
</script>
Neither option is working. Am I missing something?

You forgot to call the function. Just add
my_scripts() to the end of your file

So with a bit more digging I realised I'd forgot to close the page after chopping out the get footer and get sidebar stuff from the bottom of the page, which was causing the scripts not to load. All fixed now by adding:
<?php wp_footer(); ?>
</body>
</html>

Related

Using Slicknav with Wordpress

I've seen a few people ask about this, but I can't seem to get any other suggestions to work on my site.. I am trying to use slicknav.js on a Wordpress site I'm working on and it is not working at all. I got it to work at one point, but unfortunately had to scrap that site and start over and now I can't get it working.
I've done a little testing and just realized that NONE of my scripts are loading. wp_enqueue_scripts() isn't passing off any of my scripts at all.. Any idea what I may have done to break that?
I'm developing locally, so I can't give a link... But here is all my code.
Functions.php
<?php
// WP Enqueue Styles
function wop_styles() {
wp_enqueue_style( 'normalize_css' , get_template_directory_uri() . '/css/normalize.css' );
wp_enqueue_style( 'fontawesome_css' , 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' );
wp_enqueue_style( 'googleFonts_css' , 'https://fonts.googleapis.com/css?family=Montserrat:400,700|Roboto+Slab:400,700|Satisfy' );
wp_enqueue_style( 'slicknav_css' , 'https://cdnjs.cloudflare.com/ajax/libs/SlickNav/1.0.5.5/slicknav.min.css');
wp_enqueue_style( 'style_css' , get_template_directory_uri() . '/css/compile.css' );
}
add_action( 'wp_enqueue_scripts' , 'wop_styles' );
// WP Enqueue Scripts
function wop_scripts() {
wp_enqueue_script( 'slicknav_js' , 'https://cdnjs.cloudflare.com/ajax/libs/SlickNav/1.0.5.5/jquery.slicknav.min.js' , array('jQuery_js', 'slicknav_css') , true);
wp_enqueue_script( 'theme_js' , get_template_directory_uri() . '/js/theme.js' , array('jQuery_js'), true );
}
add_action( 'wp_enqueue_scripts' , 'wop_scripts' );
my Theme.js file:
(function($){
$('menu-header-menu').slicknav();
})(jQuery);
Finally, here is my HTML markup.
<header class="page-header"> <!--- BEGIN .page-header --->
<div class="branding">
</div>
<nav>
<?php wp_nav_menu(array('theme_location' => 'header-menu', 'container' => false,)); ?>
</nav>
</header> <!--- END .page-header --->
<footer class="page-footer"> <!--- BEGIN .page-footer --->
<?php wp_footer(); ?>
</footer> <!--- END .page-footer --->
</body> <!--- END .page-outer-wrapper -->
</html>
My footer doesn't show any scripts, and even when I change $in-footer = false, Nothin.
Obviously I have some stuff between the header and footer, but I figured these were the only real important parts..
Any ideas??
$in_footer
(boolean) (optional) Normally scripts are placed in the <head> section. If this parameter is true the script is placed at the bottom
of the <body>. This requires the theme to have the wp_footer() hook in
the appropriate place. Note that you have to enqueue your script
before wp_head is run, even if it will be placed in the footer.
If I understand correctly. You want to call your scripts in your footer but your HTML markup doesn't include a footer?
To enqueue scripts in the header ($in-footer=false) it must be before the wp_head() call.
Reference: http://codex.wordpress.org/Function_Reference/wp_register_script

jQuery conflict! Shows White Screen on POST EDIT page for WordPress

I have a made a small jQuery script to import values from other file and insert this values in WordPress POST page as Custom Meta Tags.
When I Create A New Post the form is shown below the Post content area and every thing works 100%.
The problem is if I press "Edit Post" Button/link then it loads the Post Edit page but nothing is shown. Just a White screen loads, so I cant Edit this Post.
Here is my Script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<input name="file" type="text" id="file">
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function() {
var val = $('#file').val();
$.get('import.php', {file: val}, function(data) {
result = $.parseJSON(data);
$("input[name='nick_name']").val(result.name);
$("input[name='work_city']").val(result.location);
});
});
});
</script>
<input type="button" class="button" value="GET/IMPORT">
I also tried to add this script (after jquery.min.js):
<script type="text/javascript">
$.noConflict(true);
</script>
Then Edit Post page worked but I could not use my custom form/button.
My question is: How can I load this Script without getting any conflict with WordPress Edit Post page?
If I remove:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
From my script then All pages load OK but then my custom made form/button don't work.
LATEST UPDATE: I GOT IT WORKING :D :D :D
Just testing when or where I should load this script to get my results successfully. I started editing /wp-admin/admin-header.php (I know its NOT recommended to edit CORE files but Im just doing it for debuggig!) First of all I inserted the jQuery script that Im using on Line 1 before opening of
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
Then I went to POST NEW page, I could see some different in font sizes but the function I wanted was there, I could use my button. So I opened EDIT POST page and I could see the EDIT PAGE! Now EDIT PAGE is working also. Finally I figured out if I insert this jQuery script in beginning on LINE 59 in /wp-admin/admin-header.php then every thing works 100% :D The design CSS looks good and the functionality is there!
Now I need help to insert/paste this script to LINE 59 in admin-header.php How can I do that using functions.php?
First off this seems like a bad thing to be doing editing the wordpress core. But if you want to do this, don't include jQuery again. And don't use the $ sign, see this example:
jQuery(".SomeClass").click(function(){
console.log("Some Text");
});
//Therefore you could do something like this
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.button-test-class').click(function() {
//Do what you want here, for this we'll write some text to the console
console.log("Some Text");
});
});
</script>
<input type="button" class="button-test-class button" value="Button Test">
How to add scripts The WordPress Way:
add_action( 'wp_enqueue_scripts', 'pjso_my_scripts' );
function pjso_my_scripts() {
$handle = 'script_name';
$src = '/path/to/script.js';
$deps = array(
'jquery',
);
// add any other dependencies to the array, using their $handle
$ver = 'x.x'; // if you leave this NULL,
// then it'll use WordPress's version number
$in_footer = true; // if you want it to load in the page footer
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
}
To do it only on the Edit Post screen in the backend, you can use the admin_enqueue_scripts hook combined with get_current_screen():
add_action( 'admin_enqueue_scripts', 'pjso_my_scripts' );
function pjso_my_scripts() {
$screen = get_current_screen();
if( 'post' != $screen->base || 'edit' != $screen->parent_base ) {
return; // bail out if we're not on an Edit Post screen
}
$handle = 'script_name';
$src = '/path/to/script.js';
$deps = array(
'jquery',
);
// add any other dependencies to the array, using their $handle
$ver = 'x.x'; // if you leave this NULL,
// then it'll use WordPress's version number
$in_footer = true; // if you want it to load in the page footer
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
}
That should work, though I haven't tested it.
This code can go in your theme's functions.php file, or you could write a custom plugin so that it will persist across any future theme changes.
References
wp_enqueue_script() -- note the list of scripts that WP automatically loads, which includes jQuery
get_current_screen()

wp_enqueue_script not displaying script

This is my first time using wp_enqueue_script for an IDX solution that I am trying to setup on a WordPress site. My file path is child-theme/js/idx.js
I placed this code in my functions.php file:
<?php
function wptuts_scripts_with_jquery()
{
// Register the script like this for a theme:
wp_register_script( 'custom-script', get_template_directory_uri() . '/js/idx.js', array( 'jquery' ) );
// For either a plugin or a theme, you can then enqueue the script:
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' ); ?>
and this code in my idx.js file:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" type="text/javascript" ></script>
<script src="http://tools.example.com/scripts/postmessage.min.js" type="text/javascript" ></script>
<script type="text/javascript" >
$.createDynamicFrame('http://example.example.com', 'http://example.example.com/26611/Carets/search?parentUrl=' + encodeURIComponent( document.location.href ), 'MapSearch');
This does nothing. When I use the wptuts_scripts_with_jquery()function in the functions.php with other scripts it seems to work but not with the idx.js script. Any help would be really appreciated.
Thanks!
I don't know why you are trying to include <script> tags inside an external resource but this all wrong - they should only ever contain pure javascript (this is what the browser is already expecting).
Your idx.js file should contain only this line: $.createDynamicFrame(...
Onto the reason why this erroneous file isn't being included though - the array you pass as a parameter when queueing scripts in Wordpress is a list of dependencies. I'm assuming that since you were trying to include jQuery inside your JS file - then it hasn't been previously loaded by the template? In which case, because you haven't enqueued jQuery - "custom-script" doesn't have all the required components so it doesn't get pushed onto the page.
By default wordpress already has a version of jQuery registered - if for CDN preference (or backwards comatibility sake) you need to use a different version then you should wp_deregister_script and re-enqueue it with your desired version. Otherwise your function should look like the following:
function wptuts_scripts_with_jquery(){
$path = get_template_directory_uri();
wp_enqueue_script('jquery');
wp_enqueue_script('custom-script', "{$path}/js/idx.js", array('jquery'));
}
Since nothing exists at tools.example.com/scripts/postmessage.min.js I have left this out. Also note that you can register and enqueue in a single wp_enqueue_script statement.

How can I run a jQuery method after posts are loaded in WordPress?

I'm using the Smooth Div Scroll jQuery Plugin to have a moving filmstrip on a website. The images loaded into the film strip are of a custom post type and each have a title and contain a single image. The plugin scrolls horizontally across a long div containing any amount of images. My problem is that I can scroll for a seemingly infinite amount of time even after the images are gone.
Here's the my breakdown of the problem:
I've tried using plain images instead
of the post loop, and everything
worked as expected (no infinite
scrolling).
I've tried setting scripts between document.ready and window.load, with document.ready they don't load at all.
I've tried calling a public function "recalculateScrollableArea" so that the area could be calculated after the images are loaded to no avail, then by calling an alert box in jQuery in the script I could see that it was still being called before the images were loaded.
How it should look usually:
How it looks when it over-scrolls:
The Smooth Div Scroll code and the following initializing code are both called at the bottom of the footer:
jQuery(window).load(function() {
jQuery("div#makeMeScrollable").smoothDivScroll({
autoScroll: "onstart" ,
autoScrollDirection: "backandforth",
autoScrollStep: 1,
autoScrollInterval: 15,
visibleHotSpots: "always"
});
This is what I did to try and fix the resizing:
jQuery(document).ready(function() {
jQuery("#makeMeScrollable").smoothDivScroll("disable");
});
I should also mention, the images for the posts are surrounded by "p" tags but I don't see why that would be the issue.
Thanks for reading!
EDIT:
Here is some more code, most of it is stock and working when just plain IMGs are place instead of the loop.
The base CSS and jQuery files are the same as the ones in this simple demo: http://www.smoothdivscroll.com/basicDemo.htm
jQuery and jQuery UI Imports (Working)
function jQuery_from_Google() {
if ( !is_admin() ) { // actually not necessary, because the Hook only get used in the Theme
wp_deregister_script( 'jquery' ); // unregistered key jQuery
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2'); // register key jQuery with URL of Google CDN
wp_enqueue_script( 'jquery' ); // include jQuery
}
}
// nur for Themes since WordPress 3.0
add_action( 'after_setup_theme', 'jQuery_from_Google' ); // Theme active, include function
function jQueryUI_from_Google() {
if ( !is_admin() ) { // actually not necessary, because the Hook only get used in the Theme
wp_register_script( 'jqueryui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js'); // register key jQueryUI with URL of Google CDN
wp_enqueue_script( 'jqueryui' ); // include jQueryUI
}
}
// nur for Themes since WordPress 3.0
add_action( 'after_setup_theme', 'jQueryUI_from_Google' ); // Theme active, include function
Imports take place at the bottom of the footer:
<?php // Smooth Div Scroll inport for filmstrip galleries ?>
<script type="text/javascript" src="<?php bloginfo( 'stylesheet_directory' ); ?>/javascript/filmstrip.js"></script>
<script type="text/javascript" src="<?php bloginfo( 'stylesheet_directory' ); ?>/SmoothDivScroll-1.1/js/jquery.smoothDivScroll-1.1-min.js"></script>
</body>
</html>
Here's a snippet of code for one section which uses a loop for content:
<?php if(is_page('engagements')) { ?>
<div id="makeMeScrollable">
<div class="scrollingHotSpotLeft"></div>
<div class="scrollingHotSpotRight"></div>
<div class="scrollWrapper">
<div class="scrollableArea">
<?php
$args = array( 'post_type' => 'engagement_photos' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_content();
endwhile;
?>
</div>
</div>
</div>
<?php } else if(is_page('weddings')) { ?>
Here's an example of adding an image in WordPress:
You may want to try the following code in the functions.php file.
function init_my_scripts()
{
if (!is_admin())
{
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://code.jquery.com/jquery-1.6.1.min.js');
wp_enqueue_script('jquery');
wp_deregister_script('jQuery UI Core');
wp_register_script( 'jQuery UI Core', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js'); // register key jQueryUI with URL of Google CDN
wp_enqueue_script( 'jQuery UI Core' ); // include jQueryUI
wp_register_script('filmstrip', get_bloginfo('template_directory').'/javascript/filmstrip.js');
wp_enqueue_script('filmstrip');
wp_register_script('smoothDivScroll', get_bloginfo('template_directory').'/SmoothDivScroll-1.1/js/jquery.smoothDivScroll-1.1-min.js');
wp_enqueue_script('smoothDivScroll');
}
}
add_action('init', 'init_my_scripts');
Of course, you can change the jQuery CDN to Google CDN, change 'template_directory' to 'stylesheet_directory', etc.
Found the problem, I tried putting in regular hardcoded imgs which worked fine and then wrapped them in "p" tags which produced the same issue. I guess I was just over-thinking the problem. Sorry. Now to figure out how to get the loop to just produce the imgs.

How to put my javascript in the footer

I just want to ask on how to print script 'javascript' at the footer using simple plugin. I'm using WordPress 3.0 any ideas?
Use a functions.php file inside your theme template add this :
<?php
function add_this_script_footer(){ ?>
[YOUR JS CODE HERE]
<?php }
add_action('wp_footer', 'add_this_script_footer'); ?>
For an external javascript file to be linked in the footer, use this (>= WP2.8)
function my_javascripts() {
wp_enqueue_script( 'the-script-handle',
'path/to/file.js',
array( 'jquery','other_script_that_we_depend_on' ),
'scriptversion eg. 1.0',
true);
}
add_action( 'wp_enqueue_scripts', 'my_javascripts' );
That last true means that the script should be put at the wp_footer() hook.
Hum may be it's too late to answer, but if anyone else comes here with the same problem :
There is a plugin to do this :
http://wordpress.org/extend/plugins/footer-javascript/
Or you can doing this manually by adding this short code in your functions.php :
/**
* Automatically move JavaScript code to page footer, speeding up page loading time.
*/
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_head_scripts', 5);
Use a functions.php file inside your theme (or child theme if exists) template add this:
function add_this_script_footer() {
?>
<script>
`enter code here`
</script>
<?php }
add_action('wp_footer', 'add_this_script_footer');
Simply
Upload your javascript file as a media, (the same way you will upload images and videos)
Get the link to the file, (it will look something like this http://your-domain.com/wp-content/uploads/2021/11/index.js or different depending on the site settings you have.
At the bottom of your wordpress page, add a Custom HTML link block and type <script src="/wp-content/uploads/2021/11/index.js"></script>. Do not include the http://your-domain.com.
If you are adding more custom HTML code, make sure to add the script at the end of your html code.
And there you have it.

Categories

Resources