Current Post Has Parent – Conditional Single Template

In the Bricks Facebook group, a user asks:

Hey! Anyone achieved to assign template to CPT but only to child posts? I cant figure this one out, I read smth about template score assignment but didnt really understood it. Thanks a lot!!

This Pro tutorial provides the steps to apply one of two Bricks templates to single posts (of any post type) depending on whether that post has a parent or not.

To be able to set a parent item for your CPT item make sure “Page Attributes” support is added. If using ACF to create your post type:

Step 1

Create two Bricks templates named say “Single – Post has Parent” and “Single – Post does not have a Parent” of the type “Single”.

Edit the templates and build them as needed.

Do NOT apply a template condition.

Step 2

Let’s use the bricks/active_templates filter to programmatically set a template from the previous step to single posts of testimonial post type.

Add the following in the child theme’s functions.php or a code snippets plugin:

add_filter( 'bricks/active_templates', function ( $active_templates, $post_id, $content_type ) {
	// If this is not a singular page of the specified post type, return early
	if ( ! is_singular( 'testimonial' ) ) {
		return $active_templates;
	}

	// Return if not the frontend or $content_type is not 'content'
	if ( ! bricks_is_frontend() || $content_type !== 'content' ) {
		return $active_templates;
	}
	
	// Set the template ID for the current post
	// if the current post has a parent, use 792
	// if the current post does NOT have a parent, use 794
	$active_templates['content'] = has_post_parent() ? 792 : 794;

	return $active_templates;
}, 10, 3 );

Replace testimonial with your post type. If you are setting this up for regular Pages, use page.

Replace 792 with the ID of the “Single – Post has Parent” template.

Replace 794 with the ID of the “Single – Post does not have a Parent” template.