Setting blade template programmatically by post-type

Hey there,

I have been working on setting a particular template by default for a custom post-type, the typical way I would set it is not leading to much success, having mixed results with the snippet below. If the page is ‘business_page,’ then it should pass the if condition with the correct template.

With Sage 9 any suggestions, and what I could be doing better?
Really appreciate any advice.

add_filter( 'page_template', 'cpt_template_set' );
function cpt_template_set( $page_template ) {
	global $post;
	$page_id = $post->ID;
	
	if ( get_post_type($page_id) == 'business_page') {
		$page_template = get_template_directory() . '/template-page-business.blade.php';
	}
	//var_dump( $page_id);
	//var_dump( $page_template);

	return $page_template;
}
1 Like

If I understood you correctly, you can do this by using the single-{CustomPostType}.blade.php file.

In your case, it would be something like single-business_page.blade.php

3 Likes

I agree with kaisermann. Is there a reason you’re trying to change the page template via code when you can just set up a template for the custom post type, @Daniel_Willitzer ?

@kaisermann, thank you for the reminder! Works as expected.

@kalenjohnson & @kaisermann, reason, there are multiple layouts for “business pages” that differ in style and functionality.

1 Like

I’m in a similar situation—I have a single custom post type with it’s own taxonomy, and layouts that vary based on the taxonomy in question.

I could pull layout elements in conditionally, but it seems a little cleaner to use individual template files. Am I barking up the wrong tree?

2 Likes

I try to duplicate the single.blade.php and rename to single-portfolio.blade.php which it gave me the 404 page, said Page not found. Do I need to add any filters or actions to register it with SAGE 9???

thanks!

Fixed by re-saving the permalink on the WP dashboard.