generate_element_display

The generate_element_display allows us to bypass the Display Rules, so we can enable or disable an Element under our own conditions.

This filter replaces the previous generate_header_element_display, generate_hook_element_display and generate_layout_element_display.

Display an Element to a Specific Author archive

For example, if we want to assign a specific element to Author Tom’s author archive only:

add_filter( 'generate_element_display', function( $display, $element_id ) {
    if ( 100 === $element_id && is_author( 'Tom' ) ) {
        $display = true;
    }

    return $display;
}, 10, 2 );

You need to replace 100 with the ID of your Element.

Display an Element to posts published by a Specific Author (nickname)

add_filter( 'generate_element_display', function( $display, $element_id ) {
    global $post; 

    if ( 100 === $element_id && is_single() && 'Tom' === get_the_author_meta( 'nickname', $post->post_author ) ) {
        $display = true;
    }

    return $display;
}, 10, 2 );

You need to replace 100 with the ID of your Element.

Display an Element to a Parent Page and All Child Pages

Another useful example is to set the hook to display on the parent page and all its child pages automatically:

add_filter( 'generate_element_display', function( $display, $element_id ) {
    global $post;

    if ( 100 === $element_id && (( is_page() && $post->post_parent == '415' ) || is_page(415) )) {
        $display = true;
    }

    return $display;
}, 10, 2 );

In the element, set the Display Rule to the parent page and replace 100 with the ID of your Element, and 415 with the ID of the parent page.

Display an Element to all Single Posts that are in the Subcategories of a Parent category

add_filter( 'generate_element_display', function( $display, $element_id ) {
    global $post;
    $parent_category = get_term_by( 'slug', 'parent', 'category' );
    
    if ( $parent_category ) {
        $parent_category_id = $parent_category->term_id;
        $subcategories = get_term_children( $parent_category_id, 'category' );

        // Check if the post is in the subcategories
        if ( 100 === $element_id && ( is_single() &&  has_term( $subcategories, 'category', $post ) ) ) {
            $display = true;
        }
    }

    return $display;
}, 10, 2 );

In the element, leave the locations of the Display Rule blank, replace 100 with the ID of your Element, and replace parent with the slug of your parent category.

Remove an Element when No Featured Image is Uploaded

If you would like to remove a block element page hero automatically when no featured image is uploaded instead of using the display rules manually, this snippet can be used:

add_filter( 'generate_element_display', function( $display, $element_id ) {
    if ( 100 === $element_id ) {
        if ( ! has_post_thumbnail() ) {
            $display = false;
        }
    }

    return $display;
}, 10, 2 );

You need to replace 100 with the ID of your Element.