The wp_footer
hook allows you to inject custom scripts and code before the closing </body>
tag. This is the recommended location for most JavaScript code to ensure the DOM is fully loaded.
Basic Implementation
Add this function to your child theme’s functions.php
file:
function digifusion_child_custom_footer_scripts() {
// Your custom scripts here
}
add_action( 'wp_footer', 'digifusion_child_custom_footer_scripts' );
Adding Inline JavaScript
To add inline JavaScript code directly to the footer:
function digifusion_child_add_inline_scripts() {
?>
<script>
// Custom JavaScript code
document.addEventListener('DOMContentLoaded', function() {
console.log('DigiFusion theme loaded');
// Example: Add smooth scrolling to anchor links
const links = document.querySelectorAll('a[href^="#"]');
links.forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth'
});
}
});
});
});
</script>
<?php
}
add_action( 'wp_footer', 'digifusion_child_add_inline_scripts' );
Enqueuing External JavaScript Files
For external JavaScript files, use proper enqueueing instead of direct output:
function digifusion_child_enqueue_footer_scripts() {
wp_enqueue_script(
'digifusion-child-custom',
get_stylesheet_directory_uri() . '/js/custom.js',
array(), // Dependencies
'1.0.0',
true // Load in footer
);
}
add_action( 'wp_enqueue_scripts', 'digifusion_child_enqueue_footer_scripts' );
Create /js/custom.js
in your child theme directory:
// custom.js
document.addEventListener('DOMContentLoaded', function() {
// Your custom JavaScript code here
// Example: Mobile menu toggle
const menuToggle = document.querySelector('.digi-menu-toggle');
const navigation = document.querySelector('.digi-header-nav');
if (menuToggle && navigation) {
menuToggle.addEventListener('click', function() {
document.body.classList.toggle('mopen');
});
}
});
Conditional Script Loading
Load scripts only on specific pages or conditions:
function digifusion_child_conditional_footer_scripts() {
// Only on single posts
if (is_single()) {
?>
<script>
// Post-specific JavaScript
const postContent = document.querySelector('.digi-post-content-single');
if (postContent) {
// Add reading progress indicator
const progressBar = document.createElement('div');
progressBar.className = 'reading-progress';
progressBar.style.cssText = 'position:fixed;top:0;left:0;width:0%;height:3px;background:#e74c3c;z-index:9999;transition:width 0.3s;';
document.body.appendChild(progressBar);
window.addEventListener('scroll', function() {
const scrolled = window.scrollY;
const total = document.documentElement.scrollHeight - window.innerHeight;
const progress = (scrolled / total) * 100;
progressBar.style.width = progress + '%';
});
}
</script>
<?php
}
// Only on WooCommerce pages
if (function_exists('is_woocommerce') && is_woocommerce()) {
?>
<script>
// WooCommerce-specific JavaScript
document.addEventListener('DOMContentLoaded', function() {
const quantityInputs = document.querySelectorAll('input[type="number"]');
quantityInputs.forEach(input => {
input.addEventListener('change', function() {
this.form.submit();
});
});
});
</script>
<?php
}
}
add_action( 'wp_footer', 'digifusion_child_conditional_footer_scripts' );
Adding Analytics and Tracking Scripts
function digifusion_child_analytics_scripts() {
// Only add on frontend for non-admin users
if (!is_admin() && !current_user_can('administrator')) {
?>
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID');
</script>
<!-- Custom event tracking -->
<script>
document.addEventListener('DOMContentLoaded', function() {
// Track button clicks
const buttons = document.querySelectorAll('.digi-button');
buttons.forEach(button => {
button.addEventListener('click', function() {
gtag('event', 'click', {
'event_category': 'button',
'event_label': this.textContent.trim()
});
});
});
});
</script>
<?php
}
}
add_action( 'wp_footer', 'digifusion_child_analytics_scripts' );
Passing PHP Data to JavaScript
When you need to use PHP variables in your JavaScript:
function digifusion_child_localize_scripts() {
wp_enqueue_script(
'digifusion-child-main',
get_stylesheet_directory_uri() . '/js/main.js',
array(),
'1.0.0',
true
);
// Pass data to JavaScript
wp_localize_script('digifusion-child-main', 'digiChildData', array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('digi_child_nonce'),
'homeUrl' => home_url(),
'isLoggedIn' => is_user_logged_in(),
'currentPostId' => get_the_ID()
));
}
add_action( 'wp_enqueue_scripts', 'digifusion_child_localize_scripts' );
In your /js/main.js
file:
// main.js
document.addEventListener('DOMContentLoaded', function() {
// Access PHP data
if (typeof digiChildData !== 'undefined') {
console.log('Home URL:', digiChildData.homeUrl);
console.log('User logged in:', digiChildData.isLoggedIn);
// Example AJAX request
if (digiChildData.isLoggedIn) {
fetch(digiChildData.ajaxUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
action: 'custom_action',
nonce: digiChildData.nonce,
post_id: digiChildData.currentPostId
})
})
.then(response => response.json())
.then(data => {
console.log('AJAX response:', data);
});
}
}
});
Performance Optimization
For better performance, you can defer non-critical scripts:
function digifusion_child_deferred_footer_scripts() {
?>
<script>
// Load non-critical scripts after page load
window.addEventListener('load', function() {
// Social media widgets
if (document.querySelector('.social-widgets')) {
const script = document.createElement('script');
script.src = 'https://platform.twitter.com/widgets.js';
script.async = true;
document.head.appendChild(script);
}
// Comments system
if (document.querySelector('#comments')) {
// Load Disqus or other comment system
}
});
</script>
<?php
}
add_action( 'wp_footer', 'digifusion_child_deferred_footer_scripts' );