WordPress Excerpt Function in jQuery
This guide shows how to create a custom "Read More" excerpt toggle in WordPress using a shortcode in functions.php and a jQuery fade animation.
Prerequisites
- Access to your theme's
functions.php and a custom JavaScript file (e.g. via a child theme or plugin)
- jQuery loaded on the page
Step 1: Register the Shortcode in functions.php
Add the following shortcode handler to your theme's functions.php:
function display_excerpt_function($atts, $content = null) {
return '<a id="EndExcerpt" href="#">Read More</a>'
. '<span id="hidden-content">' . $content . '</span>';
}
add_shortcode('hide-content', 'display_excerpt_function');
Step 2: Add the jQuery Toggle Script
Enqueue or paste the following in your custom JS file:
jQuery("#hidden-content, #HideExcerpt").hide();
jQuery("#EndExcerpt, #HideExcerpt").click(function() {
jQuery("#EndExcerpt, #HideExcerpt").fadeToggle();
jQuery("#hidden-content").fadeToggle("slow", "linear");
return false;
});
Step 3: Style the Read More Button
#EndExcerpt {
float: right;
padding: 4px 20px;
text-align: right;
background-color: rgb(51, 51, 51);
color: white;
margin-top: 15px;
}
Usage
Wrap hidden content in the shortcode inside any post or page:
[hide-content]This text is hidden until the user clicks Read More.[/hide-content]
Notes
- The
#HideExcerpt element is optional — add it to the shortcode output if you want a visible "Hide" button after expansion.
- Use
fadeToggle() instead of toggle() for a smoother UX.
Smooth Animated Scrolling for Same-Page Links with jQuery
This guide explains how to implement smooth animated scrolling for same-page anchor links using jQuery, with proper guards against false positives and inline handler conflicts.
Prerequisites
- jQuery 1.2 or later loaded on the page
Basic Implementation
The initial approach attaches a click handler to all links containing # in the href, then scrolls to the target element:
$(document).ready(function() {
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) + ']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html, body').animate({ scrollTop: targetOffset }, 1000);
return false;
}
}
});
});
Improved Version: Guard Against Edge Cases
The improved version uses .each() to iterate links first and binds the click handler only to valid same-page anchors. This avoids hijacking links with bare # hrefs and prevents conflicts with inline onclick handlers.
$(document).ready(function() {
$('a[href*=#]').each(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& location.hostname == this.hostname
&& this.hash.replace(/#/, '')) {
var $targetId = $(this.hash);
var $targetAnchor = $('[name=' + this.hash.slice(1) + ']');
var $target = $targetId.length ? $targetId
: $targetAnchor.length ? $targetAnchor
: false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
$('html, body').animate({ scrollTop: targetOffset }, 400);
return false;
});
}
}
});
});
Notes
- The pathname and hostname checks ensure only links pointing to the current page trigger the animation — fully-qualified, relative, and fragment-only URLs are all handled.
- The
this.hash.replace(/#/, '') guard prevents a bare # href from causing a false match in Safari.
- Binding inside
.each() (loop-first, bind-last) prevents the animation from interfering with links that have existing onclick handlers.
- Adjust the duration value (400 ms above) to control scroll speed.
Check if a Checkbox is Checked and Alert with jQuery
This guide shows how to use jQuery to detect when a checkbox is unchecked and display an alert, then force it back to a checked state — useful for enforcing terms-and-conditions acceptance.
Prerequisites
- jQuery loaded on the page
- A checkbox input with the target
name attribute
Implementation
$("input[name='checkboxesc20']").click(function() {
if ($(this).prop("checked") == true) {
// Checkbox is checked — proceed normally
} else if ($(this).prop("checked") == false) {
alert("You must agree to our T&C and Privacy Policy.");
// Force the checkbox back to checked
$("input[name='checkboxesc20']").prop('checked', true);
}
});
Notes
- Replace
checkboxesc20 with your checkbox's actual name attribute value.
- Re-checking the box after the alert prevents the user from accidentally leaving it unchecked.
- For form-level validation (on submit rather than on click), move the check into a
$('form').submit() handler and call e.preventDefault() to block submission.
Get Selected Option Value with jQuery
This guide shows how to read the currently selected value from a <select> dropdown and display it in an input field using jQuery.
Prerequisites
- jQuery loaded on the page
- A
<select> element and a text input to display the result
HTML Structure
<select id="dropdown_selector">
<option value="val1">Option 1</option>
<option value="val2">Option 2</option>
<option value="val3">Option 3</option>
</select>
<input type="text" id="showoption" placeholder="Selected value appears here">
jQuery Script
$(document).ready(function() {
// Bind change event to the select element
$('#dropdown_selector').change(function() {
// Get the currently selected option's value
var option = $(this).find('option:selected').val();
// Write it to the input field
$('#showoption').val(option);
});
});
Notes
- Use
.val() on the <select> directly as a shorthand: $(this).val() returns the selected value without needing .find('option:selected').
- To get the visible text (not the value attribute), use
$(this).find('option:selected').text().
- To read the selected value on page load (before any change), trigger the event manually:
$('#dropdown_selector').trigger('change');
Highlight Unchecked Checkboxes with jQuery
This guide shows how to visually highlight unchecked checkboxes when a submit button is clicked, using jQuery to add a CSS class to their parent elements.
Prerequisites
- jQuery loaded on the page
- Checkboxes with a shared class (e.g.
new_order) and a submit button with id submit
HTML Structure
<ul>
<li><input type="checkbox" class="new_order"> Item A</li>
<li><input type="checkbox" class="new_order"> Item B</li>
</ul>
<button id="submit">Submit</button>
jQuery Script
$('#submit').click(function() {
$('.new_order').each(function() {
if ($(this).prop('checked') === false) {
$(this).parent().addClass('incomplete');
}
});
});
CSS for the Highlight
.incomplete {
border: 1px solid orange;
background: yellow;
}
Notes
- To target a specific ancestor rather than the direct parent, pass a selector to
.parent(): $(this).parent('li').addClass('incomplete');
- To remove the highlight once the user checks the box, add a
change handler: $('.new_order').change(function() { $(this).parent().removeClass('incomplete'); });
- Combine this with actual form validation to block submission when required checkboxes are unchecked.
Add or Change Text with jQuery
This guide covers two common text manipulation patterns with jQuery: inserting text adjacent to an element, and finding-and-replacing text inside elements matching a CSS class.
Prerequisites
- jQuery loaded on the page
Insert Text After a Button
Add a legend or note immediately after a button that contains specific text:
// After the button labelled "Book now"
jQuery(":contains('Book now')").closest('button').after("Your legend text here");
// After the last submit button on the page
jQuery(":submit").last().after("Your legend text here");
Find and Replace Text Inside Elements
Use .text() with a callback to replace a substring inside all matching elements:
jQuery(document).ready(function($) {
$(".plus-table__text-inner").text(function() {
return $(this).text().replace(
"Artisan Global Discovery Fund",
"ECP Growth Companies Fund"
);
});
$(".plus-table__text-inner").text(function() {
return $(this).text().replace(
"MSCI All Country World SMID Cap Net Index in AUD",
"S&P/ASX 300 Accumulation Index"
);
});
});
Notes
- The
:contains() selector is case-sensitive.
.text() with a replacement callback strips HTML tags; use .html() if the content contains markup you want to preserve.
- JavaScript's
String.replace() only replaces the first match by default. To replace all occurrences use a global regex: .replace(/Old Text/g, 'New Text').
jQuery toggle() Method Examples
This guide demonstrates the jQuery toggle() method, which alternately shows and hides matched elements each time it is called.
Prerequisites
- jQuery loaded on the page
Basic Toggle on Button Click
Toggle the visibility of all paragraph elements when a button is clicked, with a 500 ms animation:
$(document).ready(function() {
$("button").click(function() {
$("p").toggle(500);
});
});
HTML Example
<button>Toggle Paragraphs</button>
<p>This is a paragraph with a little content.</p>
<p>This is another small paragraph.</p>
Notes
- Passing a duration (in milliseconds) to
toggle() applies a fade-like show/hide animation. Omit it for an instant toggle.
- To toggle a specific element rather than all
<p> tags, use an id or class selector: $("#myElement").toggle(500);
toggleClass() is the CSS-class equivalent — it adds the class if absent and removes it if present, which is preferable for pure visual state changes.
Change All Links on a Page to a Single URL with jQuery
This guide explains how to use jQuery to overwrite every anchor tag within a specific container class to point to a single destination URL — useful for portfolio pages where all item links should go to one procedures page.
Prerequisites
- jQuery loaded on the page
- The script placed in the specific template file where this behaviour is required (not globally)
Implementation
jQuery(document).ready(function($) {
// Redirect all links inside .caption__portfolio to a single URL
$('.caption__portfolio a').each(function() {
$(this).attr('href', 'https://example.com/your-target-page');
});
// Unwrap portfolio images (remove the wrapping anchor tag)
$('.portfolio_item_holder img').each(function() {
$(this).unwrap();
});
// Centre-align the last paragraph in each caption
$('.caption__portfolio p:nth-last-child(1)').each(function() {
$(this).attr('style', 'text-align: center');
});
});
Notes
- Place this script only in the template file for the affected page (e.g.
page-Portfolio3Cols-filterable.php) to avoid unintended side-effects on other pages.
.unwrap() removes the parent element of the matched set while keeping the matched elements in the DOM — useful for stripping generated anchor wrappers around images.
- Replace the hard-coded URL with a dynamic value if the target page changes frequently.
Set Parallax Section Background Dynamically with jQuery
This guide shows how to fix a Safari-specific issue where parallax section backgrounds fail to display, by detecting Safari via the user agent and overriding the background-attachment property with jQuery.
Prerequisites
- jQuery loaded on the page
- A parallax section with a known CSS class (e.g.
section.bzcus)
- Code placed in
footer.php (or equivalent) so it runs after the section is in the DOM
Implementation
jQuery(document).ready(function($) {
// Detect Safari (excluding Chrome on iOS which also uses Apple vendor)
var isSafari = navigator.vendor
&& navigator.vendor.indexOf('Apple') > -1
&& navigator.userAgent
&& !navigator.userAgent.match('CriOS');
if (isSafari) {
// Safari does not support background-attachment: fixed on elements
// inside overflow:hidden containers — fall back to scroll
$('section.bzcus').css('background-attachment', 'scroll');
}
});
Notes
- Safari ignores
background-attachment: fixed on elements inside scrollable containers. Switching to scroll restores the background while losing the parallax effect only for Safari users.
- The
CriOS check excludes Chrome running on iOS (which reports Apple as vendor) so the fix only targets true Safari.
- Place this script in
footer.php or load it deferred so the section element exists in the DOM when the script runs.
Hide a Specific Anchor Tag with jQuery
This guide demonstrates two techniques for handling specific anchor tags with jQuery: hiding the parent element of an anchor, and disabling the link's navigation without removing it from the DOM.
Prerequisites
- jQuery loaded on the page
Technique 1: Hide the Parent Element of an Anchor
Select the anchor by its exact href value and hide its containing element:
jQuery(document).ready(function($) {
$('a[href="https://example.com/our-people/consultant/"]').parent().hide();
});
Technique 2: Disable Navigation Without Hiding
Remove the href attribute so the anchor becomes a non-navigating element, while keeping it visible and styled as a pointer:
jQuery(document).ready(function($) {
$("a[href='https://example.com/product-category/sunglasses/']")
.removeAttr("href")
.css("cursor", "pointer");
});
Notes
- Use
.parent() to hide the containing <li> or <div> if the anchor itself has no layout footprint (e.g. inside a menu).
.removeAttr("href") makes the element inert for navigation but preserves its text and appearance. This is preferable to display:none when you still want the element visible.
- Target anchors by
href only when the URL is stable. Class or ID-based selectors are more maintainable.
Replace Text Inside a CSS Class with jQuery
This guide covers two approaches to replacing text inside elements matched by a CSS class: swapping out full element content using .replaceWith(), and updating button or link text using .text().
Prerequisites
- jQuery loaded on the page
Replace an Element's Content Entirely
Use .replaceWith() to substitute the entire matched element (including its tag) with new HTML:
jQuery(document).ready(function($) {
$("div.phone-info").replaceWith(
'<div class="phone-info">' +
'123 Example Street, City, Country<br>' +
'Ph: +1 555 123 4567' +
'</div>'
);
});
Replace Text Inside a Link or Button
Use .text() to change the visible label of all elements matching a class:
jQuery(document).ready(function($) {
// Change "Read More" link text (class: more-link)
jQuery(".more-link").text("Scopri di più");
});
Notes
.replaceWith() removes the original element from the DOM and inserts the replacement — all event handlers bound to the original element are lost.
.text(newValue) sets the text content of all matched elements. Use .html(newValue) if the replacement contains markup.
- For internationalised sites, store replacement strings in a JS object rather than hard-coding them inline.
Add target="_blank" to Links in a Specific Class with jQuery
This guide shows how to use jQuery to set target="_blank" on all anchor tags that share a specific CSS class, causing them to open in a new browser tab.
Prerequisites
- jQuery loaded on the page
- Anchor elements with a known class (e.g.
elementor-post__read-more)
Implementation
jQuery("a.elementor-post__read-more").attr('target', '_blank');
Wrap in a Document-Ready Handler (if needed)
jQuery(document).ready(function($) {
$("a.elementor-post__read-more").attr('target', '_blank');
});
Notes
- Replace
elementor-post__read-more with the actual class on your anchor tags.
- For security, always pair
target="_blank" with rel="noopener noreferrer" to prevent the new tab from accessing the opener's window object: .attr({ target: '_blank', rel: 'noopener noreferrer' })
- If the links are generated dynamically (e.g. via AJAX), run this snippet after the dynamic content is inserted, or use event delegation instead.
Disable href on Anchor Tags with jQuery
This guide covers three jQuery techniques for disabling anchor tag navigation — useful when you need to suppress links generated by a theme or plugin without editing template files directly.
Prerequisites
- jQuery loaded on the page
- Custom JS file enqueued (e.g. in
wp-content/themes/yourtheme/js/custom.js)
- All custom JS must be placed inside a
$(document).ready() wrapper
Technique 1: preventDefault()
Intercepts the click event and stops navigation while keeping the href attribute intact:
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
});
});
To target a specific link rather than all anchors:
$('a[href="https://example.com/page-to-disable"]').click(function(e) {
e.preventDefault();
});
Technique 2: removeAttr("href")
Removes the href attribute entirely so the element is no longer a navigating link:
$(document).ready(function() {
$('a.specific-class').removeAttr("href");
});
Technique 3: Return false from Click Handler
Returning false from a jQuery click handler is equivalent to calling both e.preventDefault() and e.stopPropagation():
$(document).ready(function() {
$('a.specific-class').click(function() {
return false;
});
});
Notes
- Use a precise CSS selector (id, class, or attribute) rather than a bare
'a' to avoid disabling unintended links across the site.
- Technique 1 is the cleanest for accessibility — screen readers can still read the
href value.
- Technique 2 is the most aggressive — the element loses its link semantics entirely.
- Use browser DevTools (F12 → Inspector) to find a selector specific to the link you want to disable.
Select Images from Server with jQuery (CKFinder/File Manager)
This guide shows a jQuery script that can be run in the browser console inside a file manager (such as CKFinder) to automatically select checkboxes for files that are not resized variants — i.e. original image files without dimension suffixes in their filenames.
Prerequisites
- A file manager table rendered with class
widefat (standard in WordPress media or CKFinder UI)
- jQuery available in the page context
How It Works
The script iterates every table row, inspects cell text for the presence of x (which appears in dimension strings like 300x200), and checks the row's checkbox only when no dimension string is found — selecting originals and skipping thumbnails.
Script
jQuery('.widefat').find('tr').each(function() {
var row = jQuery(this);
if (row.find('input[type="checkbox"]')) {
var columns = row.find('td:not(:first-child)');
jQuery(columns).each(function(index) {
var str = jQuery(this).text();
// Skip rows with "x" in text (dimension strings like 300x200)
// and skip the header "File" cell
if (str.indexOf('x') === -1) {
if (str !== "File") {
var checkboxid = row.find("input[type='checkbox']").prop("id");
if (checkboxid !== null) {
jQuery('#' + checkboxid).prop('checked', true);
}
}
}
});
}
});
Notes
- This script uses a simple
indexOf('x') heuristic to detect dimension strings. Extend it with a regex (e.g. /\d+x\d+/) for more precise matching: if (!/\d+x\d+/.test(str))
- Run this in the browser DevTools console while the file manager table is visible.
- The script does not submit or delete anything — it only toggles checkbox state. Always review the selection before confirming any bulk action.