This is searchable archive of our old support forums, which operated from 2012 - 2016. To find out how to get support for your current theme, please visit our support page.

Switching Template Parts in Search Results

  • Creator
    Topic
  • #13403
    srumery
    Participant

    Search results are using the same template part for all post types. Blog posts and pages work as they should but I have a couple custom post types where I need to modify the display and remove post meta in search results so I build template parts to do just that. The following code worked at one point, most likely before Jump Start v1.1.0.

    function rum_template_parts( $parts ) {
    	global $my_post_id;
    
    	// modify the content parts for search results
    	// -- blog posts, pages and events proceed as normal 
    	if ( is_search() ) {
    
    		// -- post type articles must return custom template part
    		if ( 'articles' == get_post_type() ) {
    			$parts['search_results'] = 'list_front_page';			
    		}
    
    		// -- post type resources must return custom template part
    		if ( 'resources' == get_post_type() ) {
    			$parts['search_results'] = 'grid_resource';			
    		}
    	}
    
    	return $parts;
    }
    add_filter( 'themeblvd_template_parts', 'rum_template_parts' );

    This doesn’t seem to be working now because the template parts are not being altered at each step in the loop on the search results page. Since $parts[‘search_results’] doesn’t change, it is using the standard archive display for all search results. It looks like search results may be a secondary loop so that could be where the problem is.

    I have reviewed the developer docs describing how to alter content parts as well as a post regarding Custom post formats on Search Results.

    How can I use the right content part for each unique post type display in search results?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
    Replies
  • #13408
    Jason Bobich
    Keymaster

    You want to use the filter “themeblvd_template_part” filter — no “s” — to modify the individual template part within the loop. It should look something like this:

    function my_template_part( $part, $type ) {
    
    	if ( $type == 'search_results' ) {
    
    		if ( 'articles' == get_post_type() ) {
    			$part = 'list_front_page';
    		}
    
    		if ( 'resources' == get_post_type() ) {
    			$part = 'grid_resource';
    		}
    
    	}
    
    	return $part;
    }
    add_filter( 'themeblvd_template_part', 'my_template_part', 10, 2 );

    This is newer; I don’t think it’s covered in that article.

    #13421
    srumery
    Participant

    Brilliant! This worked perfectly. Thank you so much.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.