Skip to content

Device control classes are output as visible text when core/post-featured-image has no featured image #133

Description

@Xenos1104

When using Content Control's device visibility rules on a Gutenberg core/post-featured-image block, the cc-hide-on-* classes are output as visible text if the post does not have a featured image.

Environment
WordPress: Gutenberg / native Query Loop
Content Control: 2.6.5
Block: core/post-featured-image
Content Control: Device Rules (hideOn)
Theme: Blocksy
Steps to reproduce
Create a post and add a featured image.
Add a core/post-featured-image block to a Query Loop.
Configure Content Control device rules, for example:
Desktop image: hide on mobile
Mobile image: hide on tablet and desktop
Create another post using the same Query Loop, but without a featured image.
View the Query Loop.

When a featured image exists, the classes are added correctly to the generated

element.

When no featured image exists, core/post-featured-image returns no HTML output. Content Control nevertheless tries to add the device classes.

The result is visible text such as:

class="cc-hide-on-mobile"

or:

class="cc-hide-on-tablet cc-hide-on-desktop"

being displayed on the page.

Expected behavior

If the block produces no HTML output, Content Control should simply leave the output unchanged.

In other words, if $block_content is empty and there is no HTML element to which the classes can be added, the function should return $block_content without modifying it.

Possible cause

In classes/Controllers/Frontend/Blocks.php, render_block() searches for the first HTML element:

$html_element_matches = [];
preg_match(
'/<[^>]+>/',
$block_content,
$html_element_matches,
PREG_OFFSET_CAPTURE
);

$first_element = $html_element_matches[0][0];

For core/post-featured-image without a featured image, $block_content is empty, so there is no matching HTML element.

A possible safeguard would be:

$html_element_matches = [];

preg_match(
'/<[^>]+>/',
$block_content,
$html_element_matches,
PREG_OFFSET_CAPTURE
);

if ( empty( $html_element_matches ) ) {
return $block_content;
}

$first_element = $html_element_matches[0][0];

This would prevent Content Control from attempting to inject the classes when there is no HTML element available.

The device-control functionality itself works correctly when the featured image exists; the issue appears to be specifically related to blocks that render an empty string.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions