I've created a custom block which outputs some specific data in a table, using the same class names/structure that the core Table block does.
Usually all of the CSS is loaded onto a page so my block will inherit the default table styles of a theme.
When using the new WP 2022 theme, which uses add_filter( 'should_load_separate_core_block_assets', '__return_true' ), WordPress only loads the CSS for blocks that are on the page, which means unless there's a table on the page, my block doesn't work with the rest of the theme.
I've been searching around but there doesn't seem to be a way to enqueue styles from a specific block.
I'm registering my block styles like this:
wp_register_style(
'my-block-style',
MY_PLUGIN_URL.'/blocks/manage-sessions/style.css',
array(''),
'1.0.1'
);
register_block_type(
'my-plugin/active-logins',
array(
'style' => 'my-block-style',
'editor_style' => 'my-block-editor-style',
'editor_script' => 'my-block-script',
'render_callback' => array($this, 'render_active_logins')
)
);
In my wp_register_style I've tried adding a few different dependencies inside the array, but it doesn't seem possible to require styles from a specific block.
Has anyone got any experience with this?
Based on the comment below, I've added this to my block render_callback:
if( function_exists('wp_should_load_separate_core_block_assets') ) {
if( wp_should_load_separate_core_block_assets() === true ) {
$handle = 'wp-block-table';
$core_styles = file_get_contents( includes_url( "/blocks/table/style.min.css" ) );
if( !is_rtl() ) {
$theme_styles = file_get_contents( includes_url( "/blocks/table/theme.min.css" ) );
} else {
$theme_styles = file_get_contents( includes_url( "/blocks/table/theme-rtl.min.css" ) );
}
$style_tag = "<style>$core_styles $theme_styles</style>";
}
}
Which seems to work well for the default 2022 theme, but I'm not sure it'll hold up for other themes, as I'm just fetching core WP CSS. There's no guarantee what folder structure actual themes will have, so it makes it difficult to manually fetch the CSS in this way without being able to identify a block as a dependency.