Redirect a Page to the Homepage If an Input Value Is Empty

Quick Summary
- A JavaScript check reads a form field on page load and sends the visitor to the homepage when the field is empty.
- Enqueue the script and pass get_site_url() to it with wp_localize_script(), which prints a magicalData object before the script.
- Load it only on the form page, for example with is_page(), since a missing input throws an error; the browser redirect isn't access control.
Some WordPress pages only make sense when they have data, for example a final step that expects an order ID in one of its form fields. If someone opens that page directly, the field is empty. This snippet checks the field with JavaScript and sends the visitor to the homepage when there’s no value.
It has two parts: PHP that loads the script and passes it the site URL, and the JavaScript that does the check.
Load and localize the script
Add this to your theme’s functions.php, inside a function hooked to wp_enqueue_scripts.
wp_enqueue_script('page-redirect', get_template_directory_uri().
'/scripts/redirect-page.js', array('jquery'), '1.0', true);
wp_localize_script('page-redirect', 'magicalData', array(
//'nonce' => wp_create_nonce('wp_rest'),
'siteURL' => get_site_url()
));wp_enqueue_script()loadsscripts/redirect-page.jsfrom the theme folder, with jQuery as a dependency, in the footer.get_template_directory_uri()points to the parent theme; in a child theme, useget_stylesheet_directory_uri()(see child and parent theme paths in WordPress).wp_localize_script()prints amagicalDataJavaScript object before the script, withsiteURLset toget_site_url(). The same technique can pass theme image paths to JavaScript.get_site_url()returns the WordPress address. If WordPress is installed in a subfolder,home_url()is the one that points to your homepage.
Redirect when the field is empty
Save this as redirect-page.js in the scripts folder of your theme.
jQuery(document).ready(function($) {
var siteurl = magicalData.siteURL;
//console.log(siteurl);
var order_id = document.querySelector('.final-form-order-id input').value;
if (order_id == '') {
console.log('No Order ID');
window.location.href = siteurl;
} else {
console.log(order_id);
}
});- It reads the value of the input inside
.final-form-order-id. Change this selector to match your form field. - If the value is empty,
window.location.hrefsends the visitor tomagicalData.siteURL. Otherwise it logs the order ID to the console. - On a page without that input,
querySelector()returnsnulland the script throws an error. Load it only on the page with the form, for example by wrapping the enqueue call in anis_page()check. - The redirect happens in the browser, so it’s a convenience, not access control. To block a page on the server, check the visitor in
template_redirect, as in disabling direct access to a WordPress page.

