[WP] Overriding default Gutenberg gallery block

To override the default Gutenberg gallery with the RoyalSlider on the frontend:

  1. Create "gallery" type of slider.
  2. Add the code below to your theme functions.php.
  3. Replace royalslider="1" with the ID of the slider that you created.
  4. Go to RoyalSlider Settings page and check an option to include JS/CSS files on all pages (as auto-detection of the shortcode will not work).
function rs_override_gallery_block($block_content, $block) {
    if ($block['blockName'] !== "core/gallery") {
        return $block_content;
    }

    $ids = array();

    // Support 5.9+ galleries
    if (array_key_exists('innerBlocks', $block) && is_array($block['innerBlocks'])) {
        foreach($block['innerBlocks'] as $innerBlock) {
            if (isset($innerBlock['blockName']) && $innerBlock['blockName'] === 'core/image') {
                $ids[] = $innerBlock['attrs']['id'];
            }
        }
    }

    // Support older galleries
    if (array_key_exists('attrs', $block) && is_array($block['attrs'])
        && array_key_exists('ids', $block['attrs']) && is_array($block['attrs']['ids'])) {
        $ids = $block['attrs']['ids'];
    }
    
    if (empty($ids)) {
        return $block_content;
    }

    return do_shortcode('[gallery royalslider="1" ids="' . implode(',', $ids) . '"]');
    
}
add_filter('render_block', 'rs_override_gallery_block', 11, 2);