Adding Custom Post Types to Omnisearch in Jetpack

omnisearch-jetpackToday I started playing with Omnisearch found in the Jetpack plugin. While this quick tip really just begins to touch the surface of bending this awesome search feature to do our bidding, I wanted to share some findings that I think will help some others.

By default, Omnisearch searches the default post types like pages, posts, comments and plugins. This is cool, but what about our Custom Post Types? There’s plenty of WordPress installs out there with 2, 3, maybe even 15 post types! What about those posts? What if we want to search those too?

Well, thankfully, this is pretty straightforward to add :)

In your functions.php add this code for each post type and the ability to search those is available via Omnisearch. Now, this is only available the back-end of WordPress at the moment. I’m working a plugin that will bring this to the front-end and allow you to customize it further (at least trying to do so when time permits it…).

<?php
    // Add our $post_type_name to Omnisearch!
    if ( class_exists( 'Jetpack_Omnisearch_Posts' ) ) {
        class CG_Post_Type_Omnisearch extends Jetpack_Omnisearch_Posts {
            var $post_type = 'post-type-id-here';
        }
        new CG_Post_Type_Omnisearch;
    }
?>

Quick explanation of the code here. For each post type, we need to create a new inheritance class. Right now, the Jetpack_Omnisearch_Posts class we are extending uses get_post_type_object() which sadly accepts a single post type as a string :( This means, we cannot just toss it an array of post types (which is most ideal).

Anyways, that’s my quick tip for today! I’m off to bed :)

To use this code, just rename the CG_Post_Type_Omnisearch class to something unique for each instance you create and pass the post type id and now you’ll see it in the search results!

omnisearch-custom-post-types