Black Friday Sale: Save 50% on Pro Plugins & Books w/ code BF2026
Web Dev + WordPress + Security

Conditionally Load WordPress Pages

Need to load a WordPress page conditionally? For example, perhaps you need a “special” page to appear for search results? Yes? This simple PHP/JavaScript solution may be just what the doctor ordered!

Simply replace “condition” with the required condition (or delete the if (condition) {} qualifier entirely), and then change the path and file names to suit your specific needs:

<?php
if (condition) {
	
	echo ("
		<script type='text/javascript'>
			parent.location='http://www.domain.com/path/to/file.html';
		</script>
	");
	
} else {
	
	echo ("
		<script type='text/javascript'>
			parent.location='http://www.domain.com/path/to/other-file.html';
		</script>
	");
	
} ?>

Specifically, I employ the following trickery in my Killer WordPress theme:

.
.
.
<?php endwhile; else: ?>
	
	<?php echo ("
		<script type='text/javascript'>
			parent.location='http://example.com/subdirectory/?p=58';
		</script>
	"); ?>
	
<?php endif; ?>

The previous code chunk returns a specially designed search results page that is specifically tailored to suit the Killer theme. Works wonders.

About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
GA Pro: Add Google Analytics to WordPress like a pro.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Digging Into WordPress: Take your WordPress skills to the next level.
Thoughts
Echotainment: watching your favorite shows over and over because all the new stuff sucks.
I wish everyone could offline meet all of their online friends.
Rediscovering the Vivaldi browser, excellent so far. Elegant, lightweight, and super fast.
Fun tool for visualizing how different internet protocols work.
Working on a complete redesign of Perishable Press :)
The Office is Cheers with more irony.
More fine-grained control of macOS screen brightness: hold down Option + Shift before pressing either of the brightness keys. You get 64 increments instead of the usual 16.
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.