How To Exclude Page Permanently In WordPress Without Using Any Plugin

Excluding page in WordPress is fairly easily when we were given some particular function in WordPress to list out pages  such as wp_list_pages or get_pages where these methods all gives us certain parameter for us to exclude certain  pages that we do not wish to display. And these methods are usually used on WordPress theme although occasional we would put them into WordPress plugin for other reason. However, using these methods will only exclude page on the THAT particular function call which really doesn't suit my need. I want something permanent which excludes every page whenever i use those methods. If you are like me who do not wish to use plugin such as the Exclude Pages plugin by Simon for whatever reason you have (mine was because of efficiency and customization wise), this may be an article that will definitely help you.

Excluding Page Permanently In WordPress

Anything that you wished to permanently done on WordPress will usually associate closely with action or filter hook in WordPress. In this case where we want to exclude page permanently, we will use filter hook.

add_filter('wp_list_pages_excludes', array($this, 'page_filter'));
function page_filter($exclude_array) {
	global $wpdb;
	$table = $wpdb->prefix . "posts";
	$sql = "SELECT ID FROM ".$table." WHERE post_title ='Exclude' OR post_title ='This' OR post_title ='Pages' OR post_title ='Search'";
	$id_array = $wpdb->get_col($sql);
	$exclude_array=array_merge($id_array, $exclude_array);
	return $exclude_array;
}

The method we will be using on our filter would be wp_list_pages_excludes which helps to exclude pages. For my case, i wanted to exclude some of the page in WordPress and when i said some i meant more than one. Hence, i wrote my own sql query and retrieve as an array of id's. This way, we can merge with the one that you or anyone who has already excluded and return to the core function to deal with it. (this way we reduce the number of sql query needed to retrieve the same amount of id's, if we use get_post method there will be 4 additional query instead of one.)

For people who are not familiar to what i am talking about, you can just copy and paste the above code into your function.php file in your theme and change post_title = 'Exclude' and post_title etc. to your own page name instead of Exclude, This and Pages. Cheers~