Snippet: How to Include Post Thumbnails in the Modal Search
We decided to not display images in the ajax search because it will slow down the rendering of your search results and for most sites they aren't needed. If we get a lot of requests we may add an option built-in to enable thumbnails, but for the time being you can use the code snippet below.
The default AJAX search modal in Total features a minimal and modern entry template design that doesn't include any images in order to provide it's users with the fastest results possible. Below is a snippet showing how you can customize the ajax template to include the post thumbnails.
/**
* Modify data passed to the ajax search.
*
* @see Total/inc/search/ajax.php
*/
add_filter( 'totaltheme/search/ajax/post_data', function( $data, $post ) {
if ( has_post_thumbnail( $post ) ) {
$data['thumbnail_url'] = get_the_post_thumbnail_url( $post, 'thumbnail' ); // be sure to modify the size
} else {
$data['thumbnail_url'] = 'PLACEHOLDER IMAGE URL'; // URL to a placeholder image for entries missing images
}
return $data;
}, 10, 2 );
/**
* Modify the ajax search template.
*
* @see Total/inc/search/modal.php
*/
add_filter( 'totaltheme/search/modal/result_template', function( $template ) {
// Open link
$template = '<a href="https://totalwptheme.com/docs/snippets/modal-search-thumbnails/" class="wpex-search-modal-result wpex-text-current wpex-hover-text-current wpex-no-underline wpex-block wpex-py-20 wpex-px-30 wpex-border-0 wpex-border-b wpex-border-solid wpex-border-main wpex-text-1 wpex-transition-300">';
// Open inner flex container
$template .= '<div class="wpex-flex wpex-flex-col wpex-sm-flex-row wpex-gap-20">';
// Display image
$template .= '<div style="width:200px"><img class="wpex-w-100 wpex-h-100 wpex-object-cover" src="{{thumbnail_url}}"></div>';
// Display content (type, title, excerpt)
$template .= '<div class="wpex-flex-grow"><div class="wpex-search-modal-result__type wpex-mb-10"><span class="wpex-inline-block wpex-surface-3 wpex-text-3 wpex-dark-mode-text-2 wpex-rounded-sm wpex-leading-none wpex-p-5 wpex-text-xs">{{tag}}</span></div><div class="wpex-search-modal-result__title wpex-heading wpex-mb-5">How to Include Post Thumbnails in the Modal Search</div><div class="wpex-search-modal-result__excerpt wpex-text-pretty wpex-last-mb-0">{{excerpt}}</div></div>';
//Close inner flex container
$template .= '</div>';
// Close link
$template .= '</a>';
// Return template
return $template;
} );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
We recommend Code Snippets (100% Free) or WPCode (sponsored)