Skip to main content

Load Benecaster’s front-end styles into the block editor

Free Intermediate

If you wrap a Benecaster shortcode in a Gutenberg block (usually previewed through ServerSideRender) or an Elementor widget, the preview renders the right HTML with none of its styling unless you load Benecaster’s stylesheet into the editor. That looks like the block is broken. This recipe loads the styles your block needs, in the editor only.

Benecaster registers every front-end script and style handle on init, so the handles exist in wp-admin, the block editor, the block-renderer preview request and admin-ajax — not only on a front-end page load. Registering is not loading: on the front end, each file is still added to a page only when the shortcode that needs it renders there.

The handles you can load: benecaster-frontend, benecaster-qrcode-lib, benecaster-subscribe (script and style), stripe-js, benecaster-account, benecaster-account-profile, benecaster-billing-portal (script and style), benecaster-buyups, benecaster-cadence-switch, benecaster-badges, benecaster-supporter-wall and benecaster-listener-support (script and style). Integrations depend on these names, so they are kept stable.

Enqueue in the editor only. enqueue_block_assets also fires on the front end, and every Benecaster shortcode already loads its own files when it renders. Enqueueing them unconditionally puts them on every page of the site, whether or not the block is there. The is_admin() guard is the point of the example.

Loading a script does not make a preview interactive. A ServerSideRender preview is static HTML injected after the page loads, so benecaster-frontend — which fills in the QR code and wires up the copy button — does not run against it on its own. Call window.benecasterFrontend.init( container ) once the preview has mounted, and again after each re-render; it is safe to repeat. See Make QR codes and copy buttons work in a block or Elementor preview.

Keeping a Benecaster file off a page. Use wp_dequeue_style() or wp_dequeue_script() on the handle. Removing Benecaster’s callback from wp_enqueue_scripts with remove_action() does nothing, because the handles are registered on init.

Code

<?php
// enqueue_block_assets fires for the editor canvas AND the front end, so this
// styles the preview without adding anything to pages that do not use the block.
add_action( 'enqueue_block_assets', function () {
    if ( ! is_admin() ) {
        return; // On the front end the shortcode enqueues its own styles when it renders.
    }
    wp_enqueue_style( 'benecaster-subscribe' );
    wp_enqueue_style( 'benecaster-supporter-wall' ); // pulls in benecaster-badges
} );

View on GitHub →

Need this built rather than just documented? See our services →