WordPress

Include All Custom Post Types In WordPress Search

Since WordPress version 3.0 you can now create your own custom post types. WordPress already comes with post types for things such as posts, pages, attachments, revisions and menus.

Custom Post types allow you to create your own content item. These are commonly used for portfolio slides and news articles.

The problem with custom post types is that they are not included in the WordPress search functionality you can only see posts and pages.

Search Add the following to your functions.php file to include all post types in the search results.

<?php
function include_post_types_in_search($query) {
	if(is_search()) {
		$post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
		$searchable_types = array();
		if($post_types) {
			foreach( $post_types as $type) {
				$searchable_types[] = $type->name;
			}
		}
		$query->set('post_type', $searchable_types);
	}
	return $query;
}
add_action('pre_get_posts', 'include_post_types_in_search');
?>
Back to top ^

Join Paulund

  • Access 100s of premium tutorials and downloadable content
  • Members content consists of premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • No ads

Join Paulund