wp_enqueue_script not displaying script - javascript

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.

Related

How to add JavaScript file to WordPress Website

I was developing a web form that will be used to collect data. I needed to attach it to my WordPress website. I have been successful attaching the HTML and CSS files, so that they can blend with the theme of the website, however, I have been unsuccessful trying to add the JavaScript file.
I have followed several guides on how to but I have not been successful. I tried the enqueue_script approach but it didn't work. Here is samples of my code from the functions.php file
<?php
/**
* Income School functions and definitions
*
* #link https://developer.wordpress.org/themes/basics/theme-functions/
*
* #package Income_School
*/
add_action( 'wp_enqueue_scripts', 'form_enqueue_style' );
function form_enqueue_script() {
wp_enqueue_script( 'form-js', get_template_directory_uri() . '/js/form.js', array(), false, true);
}
add_action( 'wp_enqueue_scripts', 'form_enqueue_script' );
In my theme folder where the above functions.php can be found, i also created js folder inside my theme folder where i placed my javascript file. However when I try to load my site, the above script cannot come into the footer. While as for the CSS, I just added it simply while I was adding the HTML code in the block, through the Scripts n Styles plugin. Kindly assist me so I can be able to ensure my JS is working well.
function my_theme_name_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_name_scripts' );
Also make sure the file is under the correct path in your theme.
I have an old PHP app here, that imports js file with an HTML script tag. After this import, I'm able to use the js functions inside other HTML components such as input. It's a simple solution you already tried?
<script language="javascript" type="text/javascript" src="lib/ajax_search.js"></script>
The function searchOrcSuggest() is inside my js file imported with html.
<input name="descricao[<?php echo $row1['codigo']?>]" id="descricao<?php echo $row1['codigo']?>" value="<?php echo $row1['descricao']?>" type="text" class="forms" size="45"
onkeyup="searchOrcSuggest(this, 'codigoprocedimento<?php echo $row1['codigo']?>', 'particular<?php echo $row1['codigo']?>', 'convenio<?php echo $row1['codigo']?>', 'search<?php echo $row1['codigo']?>', <?php echo $codigo_convenio?>);"
autocomplete="off" />
Also this app have other manner to pass js functions by an js file named script.js.php, don't ask me why!
And the import of this archive made like:
<script language="javascript" type="text/javascript" src="lib/script.js"></script>
Here is the file if you want to see it
link to file

How to enqueue script to archive head with themes' function.php?

In my theme there is a the category.php template for the archives of certain categories. I modified this file but to have an effect I need to add some javascript to the head of category.php file. Within that file there is the expression get_header();
I opened my themes' header.php and saw that all script files seem to be initialized by this function: wp_head();
So I guess I'll have to modify my theme's functions.php to enqueue my script to the head of the archive template.
But how to do that? How could I filter for category.php? During my research I found this function: is_category() - but it works only for template files. I was able to add my javascript files to the head by adding this to my header.php below the wp_head(); function:
if(is_category()){
echo '<script type="text/javascript" src="'.get_bloginfo("wpurl").'/wp-content/themes/my_theme/js/jquery-2.1.1.min.js'.'"></script>';
echo '<script type="text/javascript" src="'.get_bloginfo("wpurl").'/wp-content/themes/my_theme/js/my_script.js'.'"></script>';
}
This works but doesn't seem to be the elegant/proper way to do it. I read several times that one always should use enqueue_script functions to add script. So what is best practice and how to do it?
You have the right idea. You'll want to enqueue the scripts, but only if you're on a category archive page. Also, WordPress includes jQuery by default, so there's no reason to include your own. Keep in mind that this will mean you'll need to adhere to the noConflict mode wrappers.
function enqueue_my_so_scripts() {
if ( is_category() ) {
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/my_script.js', array('jquery'));
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_so_scripts' );

Wordpress Theming: add custom scripts and jquery the correct way

Just took over a wordpress project. The former developers screwed up the theming so it prevents my ajax forms (gravityform) from working correctly. Proplem is the way they add jquery and custom js in header.php:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/slides.min.jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/script.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/tabs.min.js"></script>
I am totaly new to wordpress theming thought, how would I correctly add those scripts in my functions.php using wp_register_script and wp_enqueue_script.
How do I find out which script depends on the others? like the correct order of calling them?
EDIT
I made it to include the scripts the proper way via wp_enqueue_scripts. But now I am facing strange JS errors.
TypeError: $ is not a function
It works when I substitute the $ by jQuery. But this cant be a solution. Why does this error appear anyways?
The best way to avoid asset conflicts is by properly enquing the files. To do this you must use wp_enqueue_script
a good way to do this is to put it as part of a function in your functions.php file like so
create a function
insert wp_register_script into the function
then insert wp_enqeue_script into the function
use add_action(), to initlize the enqueue-ing process
so -
function load_scripts() {
wp_register_script( 'script-name', get_template_directory_uri() . '/js/script.js', array( 'scriptyouwillwaittobeloaded' ) );
wp_enqueue_script( 'script-name' );
}
add_action('wp_enqueue_scripts', 'load_scripts');
In this example the function load_scripts() would then be called in the header.php file. Take a look at wp_register_script as well to get a better understanding of the arguments for that as well, but in summary -
first argument: is the name you want to use as reference to this script
second argument: is the actual link to the script
third argument: is the script that you want to load before this script (the script you want to wait for before this script loads)
and for wp_enqueue_script, the argument is merely a reference to the name (the first argument of wp_register_script)
the add_action function arguments:
first argument: the function you are "hooking" into
second argument: the function you created that will be "hooked"
To note - you can load as many scripts as you would like in this function, this is just an example of loading a single script.
What it looks like the dev's did was just to use a simple reference. If you would like to enqueue a WP script look at wp_enqueue_script
I don't believe the scripts will depend on anything other than a specific version of jquery.
this is how they do it:
<?php
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/custom_script.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>

Load swiffy page as banner

I have been trying to load the html page genereated by swiffy into my site banner. I tried iframes as was suggested in the google FAQ, but when links are clicked they only open in the iframe as per usual, but I need them to open on the current page so I tried breaking up the swiffy code into a javascript file and calling it in as shown below. I am currently using word press, which means this is all being loaded from a header.php file, and have been trying the following code with no luck. Any suggestions?
<div id="home-banner" width="916px" height="200px">
</div>
<script src="http://www.gstatic.com/swiffy/v3.9/runtime.js"></script>
<script type="text/javascript" src="http://www.goaefis.com/Banner.js">
var stage = new swiffy.Stage(document.getElementById('home-banner'), swiffyobject);
stage.start();
</script>
You need to deregister the WordPress jquery so you can use the google code. You can save the script inside the <script></script>tags as a separate document. For this example I'll call it swiftfyobject.js. It will need to go in the theme folder inside a folder named js. You can then call the script from within the themes function.php file.
Here is how it should look:
The swiffyobject.js file that goes in the js folder:
var stage = new swiffy.Stage(document.getElementById('home-banner'), swiffyobject);
stage.start();
The code for the functions.php file:
function add_themescript(){
if(!is_admin()){
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://www.goaefis.com/Banner.js');
wp_enqueue_script( 'swiffyobject', get_template_directory_uri() . '/js/swiffyobject.js', array('jquery'));
}
}
add_action('init','add_themescript');
That should get you going if there aren't any conflicts with other code in the theme or plug-ins you use.

Adding <script> to WordPress in <head> element

I'm trying to insert this code:
<script type="text/javascript">
some Javascript codes comes here
</script>
to WordPress' <head></head> section in front end and in admin panel
E.g., Joomla! 1.6 has an API that allows this:
$doc =& JFactory::getDocument();
$doc->addCustomTag($headTag);
I need to add different things for different pages. For example:
Page 1
I need to add
<link rel="alternate" type="application/rss+xml" title="feed title" href="feed url" />
For a few pages
Page 2
I need to add
<script type=\"text/javascript\" src=\"" . LIVE_SITE .
"/wp-content/plugins/jobs/lknlibrary/js/ajax.js\"></script>
<script type=\"text/javascript\">
var ajax = new sack();
var currentClientID=false;
function getClientData()
{
var clientId = document.getElementById('db_country_id').value.replace(/[^0-9]/g,'');
ajax.requestFile = '" .BASE_PATH . "/wp-content/plugins/jobs/com_jobs_admin/tasks/get_location_data.php?task=get_location_data&name=db_parent_id&getClientId='+clientId; // Specifying which file to get
ajax.onCompletion = showClientData; // Specify function that will be executed after file has been found
ajax.runAJAX(); // Execute AJAX function
}
function showClientData()
{
clearJS = ajax.response;
var strTagStrippedText = clearJS.replace(/(<\s*\/?\s*)div(\s*([^>]*)?\s*>)/gi ,'');
document.getElementById('locationsDiv').innerHTML=strTagStrippedText ;
}
function initFormEvents()
{
if (document.getElementById('db_country_id')){
document.getElementById('db_country_id').onchange = getClientData;
document.getElementById('db_country_id').focus();
}
}
window.onload = initFormEvents;
</script>
for a few pages
Page 3
I need to add
<link rel="stylesheet" type="text/css" href="/wordpress/wp-content/plugins/jobs/lknlibrary/js/tabs/tab.webfx.css" />
for a few pages
I have 70+ pages in admin panel like those above.
Trying to manage the header of the WordPress with the example is a bit difficult.
In your theme's functions.php:
function my_custom_js() {
echo '<script type="text/javascript" src="myscript.js"></script>';
}
// Add hook for admin <head></head>
add_action( 'admin_head', 'my_custom_js' );
// Add hook for front-end <head></head>
add_action( 'wp_head', 'my_custom_js' );
For anyone else who comes here looking, I'm afraid I'm with #usama sulaiman here.
Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.
Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.
Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.
Something along the following in a plugin file is what you are looking for:
<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI:
Plugin URI:
*/
function $yourJS() {
wp_enqueue_script(
'custom_script',
plugins_url( '/js/your-script.js', __FILE__ ),
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', '$yourJS' );
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
function prefix_add_my_stylesheet() {
wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
wp_enqueue_style( 'prefix-style' );
}
?>
Structure your folders as follows:
Plugin Folder
|_ css folder
|_ js folder
|_ plugin.php ...contains the above code - modified of course ;D
Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.
Elaborating on the previous answer, you can gather all the required snippets before outputting the header, and only then use an action hook to inject all you need on the head.
In your functions.php file, add
$inject_required_scripts = array();
/**
* Call this function before calling get_header() to request custom js code to be injected on head.
*
* #param code the javascript code to be injected.
*/
function require_script($code) {
global $inject_required_scripts;
$inject_required_scripts[] = $code; // store code snippet for later injection
}
function inject_required_scripts() {
global $inject_required_scripts;
foreach($inject_required_scripts as $script)
// inject all code snippets, if any
echo '<script type="text/javascript">'.$script.'</script>';
}
add_action('wp_head', 'inject_required_scripts');
And then in your page or template, use it like
<?php
/* Template Name: coolstuff */
require_script(<<<JS
jQuery(function(){jQuery('div').wrap('<blink/>')});
JS
);
require_script(<<<JS
jQuery(function(){jQuery('p,span,a').html('Internet is cool')});
JS
);
get_header();
[...]
I made it for javascript because it's the most common use, but it can be easily adapted to any tag in the head, and either with inline code or by passing a href/src to an external URL.
If you are ok using an external plugin to do that you can use Header and Footer Scripts plugin
From the description:
Many WordPress Themes do not have any options to insert header and
footer scripts in your site or . It helps you to keep
yourself from theme lock. But, sometimes it also causes some pain for
many. like where should I insert Google Analytics code (or any other
web-analytics codes). This plugin is one stop and lightweight solution
for that. With this "Header and Footer Script" plugin will be able to
inject HTML tags, JS and CSS codes to and easily.
One way I like to use is Vanilla JavaScript with template literal:
var templateLiteral = [`
<!-- HTML_CODE_COMES_HERE -->
`]
var head = document.querySelector("head");
head.innerHTML = templateLiteral;

Categories

Resources