Spring Sale! Save 30% on all books w/ code: PLANET24
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\">
		<!--//--><![CDATA[//><!--
		
		parent.location='http://www.domain.com/path/to/file.html';
		
		//--><!]]>
		</script>
	");
	
} else {
	
	echo ("
		<script type=\"text/javascript\">
		<!--//--><![CDATA[//><!--
		
		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\">
		<!--//--><![CDATA[//><!--
		
		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 = Fullstack Developer. Book Author. Teacher. Human Being.
.htaccess made easy: Improve site performance and security.
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 »
USP Pro: Unlimited front-end forms for user-submitted posts and more.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.