Parent pages filter function your WordPress admin section

If your WordPress Blog has a lot of pages (not posts) it becomes very hard to select them in the  pages list (WordPress back-end). A select menu with all the parent (top) pages would be a great and useful filter function (like the categories filter in the posts section).

Check this comment for a modified function which is able to filter grouped products in WooCommerce.

The function below will add the select menu with the parent pages as a filter:

function fws_admin_posts_filter( $query ) {
    global $pagenow;
    if ( is_admin() && $pagenow == 'edit.php' && !empty($_GET['my_parent_pages'])) {
        $query->query_vars['post_parent'] = $_GET['my_parent_pages'];
    }
}
add_filter( 'parse_query', 'fws_admin_posts_filter' );

function admin_page_filter_parentpages() {
    global $wpdb;
    if (isset($_GET['post_type']) && $_GET['post_type'] == 'page') {
		$sql = "SELECT ID, post_title FROM ".$wpdb->posts." WHERE post_type = 'page' AND post_parent = 0 AND post_status = 'publish' ORDER BY post_title";
		$parent_pages = $wpdb->get_results($sql, OBJECT_K);
		$select = '
			<select name="my_parent_pages">
				<option value="">Parent Pages</option>';
		$current = isset($_GET['my_parent_pages']) ? $_GET['my_parent_pages'] : '';
		foreach ($parent_pages as $page) {
			$select .= sprintf('
				<option value="%s"%s>%s</option>', $page->ID, $page->ID == $current ? ' selected="selected"' : '', $page->post_title);
		}
		$select .= '
			</select>';
		echo $select;
	} else {
		return;
	}
}
add_action( 'restrict_manage_posts', 'admin_page_filter_parentpages' );

How-to use this PHP code

Open the file named “functions.php” which is inside your themes directory and copy the code into this file and re-visit the pages section.

This function as based on some code I found at WP-Snippets.

Tip! If you need more or better filter options, try Admin Columns. You need to buy the PRO version to use all features, but it’s worth any penny!