WordPress Query Pages By Page Template – Go To Page On Change
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