Check Post if it is a Child Post or not, Dynamic Tag Bricks Builder

If the page has a parent, it outputs the text child.

If the page does not have a parent, it outputs the text nochild.

Tag: {is_child_page}

Can be used with any post or page or post type or inside a loop.

<?php

// TAG : {is_child_page}
// This tag checks if the current page/post has a parent and returns 'child' or 'nochild'.


/**
 * 1. Register the dynamic tag so it appears in the Bricks editor dropdown.
 */
add_filter( 'bricks/dynamic_tags_list', 'register_is_child_page_tag' );
function register_is_child_page_tag( $tags ) {
    $tags[] = [
        'name'  => '{is_child_page}',
        'label' => 'Conditional: Is Child Page',
        'group' => 'Custom Conditionals', // You can change this group name
    ];

    return $tags;
}

/**
 * 2. Render the value of the dynamic tag.
 * This is the main function that generates the output for conditions and most contexts.
 */
add_filter( 'bricks/dynamic_data/render_tag', 'render_is_child_page_tag', 10, 3 );
function render_is_child_page_tag( $tag, $post, $context = 'text' ) {
    // Ensure we are only targeting our custom tag
    if ( $tag !== 'is_child_page' ) {
        return $tag;
    }

    // Check if the current post object is valid and has a parent.
    // In WordPress, a post's 'post_parent' ID will be 0 if it has no parent.
    if ( $post && $post->post_parent > 0 ) {
        return 'child';
    }

    // If it has no parent, return 'nochild'
    return 'nochild';
}


/**
 * 3. Allow the tag to be rendered inside content fields (like Rich Text).
 * This function finds our tag within a string and replaces it with the correct value.
 * This part is crucial for making the tag work everywhere.
 */
add_filter( 'bricks/dynamic_data/render_content', 'render_is_child_page_tag_in_content', 10, 3 );
add_filter( 'bricks/frontend/render_data', 'render_is_child_page_tag_in_content', 10, 2 ); // For frontend rendering
function render_is_child_page_tag_in_content( $content, $post ) {
    // Check if our tag exists in the content string
    if ( strpos( $content, '{is_child_page}' ) === false ) {
        return $content;
    }

    // Call our main rendering function to get the 'child' or 'nochild' value
    $replacement_value = render_is_child_page_tag( 'is_child_page', $post );

    // Replace the placeholder with the actual value
    $content = str_replace( '{is_child_page}', $replacement_value, $content );

    return $content;
}