Search code examples
wordpresscustom-post-typecustom-fields

Customize search results for Custom Post Types


I am writing a Wordpress plug-in that creates several Custom Post Types (CPT). For they have their own custom fields, that need to be displayed in the search results, I need to customize the search results output.

Do I need to write my own theme for that or is there a hook (or other way) to solve this in my plug-in code?


Solution

  • You could hook into get_the_content and get_the_excerpt filters and test with is_search() to see if you should alter the returned value or not.

    Not tested, but this is the idea:

    add_filter( 'get_the_excerpt', 'my_search_excerpt' );
    add_filter( 'get_the_content', 'my_search_excerpt' );
    
    function my_search_excerpt( $content ) {
        if ( is_search() ) {
            $content = 'This is a search excerpt for ' . get_the_title();
            // maybe add a read more link
            // also, you can use global $post to access the current search result
        }
        return $content;
    }