WordPress Query Pages By Page Template – Go To Page On Change


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WordPress Query Pages By Page Template – Go To Page On Change

Today we’re going to look at a quick post snippet that I surprising use quite often. First, I often find it necessary to query posts based on a custom page template. This query is fairly simple as the post template is stored as a meta key value in the database. Therefore, our query looks like this:

<?php $pages = get_pages(array(
	'meta_key' => '_wp_page_template',
	'meta_value' => 'custom-page-template.php',
));
foreach($pages as $page){ ?>
<h3><?php echo $page->post_title; ?></h3>
<?php } ?>

However, in several occasions I’ve wanted to put this snippet within a form select dropdown that would then go the the page URL on change. In order to accomplish this, I’ve combined the above function within a form like so:

<form name="myform">
    <select class="page-jump" name="menu" onChange="window.document.location.href=this.options[this.selectedIndex].value;" value="GO">
        <option selected="selected">Select A Page</option>
        <?php $pages = get_pages(array(
			'meta_key' => '_wp_page_template',
			'meta_value' => 'custom-page-template.php',
		));
		foreach($pages as $page){ ?>
        <option value="<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?></option>
        <?php } ?>
    </select>
</form>

Just like that, we’ve created a nice form that queries in all WordPress pages with the custom page template of custom-page-template.php and then added functionality so on select change, we will go to the page permalink.

That’s it for the day, I hope it is useful!


Comments:

Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!