godaddy-wordpress / coblocks

A suite of professional page building content blocks for the WordPress Gutenberg block editor.
https://wordpress.org/plugins/coblocks/
GNU General Public License v2.0
749 stars 145 forks source link

HOW: Using the lightbox on standard WordPress images/galleries #1425

Closed arraypress closed 4 years ago

arraypress commented 4 years ago

As per discussion with my friend Rich Tabor, I wanted to use the beautiful CoBlocks included lightbox on other elements throughout my site to minimise bloat and plugin requirements.

The issue is the lightbox JS file required is loaded dynamically when a CoBlocks "carousel" block is used via has the has_block function, so I had to build a custom function within my child theme to get around this, here it is:

/**
 * Load CoBlocks Carousel script when 'gallery' block is used.
 *
 * @since 1.0
 */
function ds_load_coblocks_carousel_script() {

  if ( ! class_exists( 'CoBlocks' ) ) {
    return;
  }

  // Define where the asset is loaded from.
  $dir = CoBlocks()->asset_source( 'js' );

  // Carousel block.
  if ( has_block( 'gallery' ) ) {
    wp_enqueue_script(
      'coblocks-lightbox',
      $dir . 'coblocks-lightbox.js',
      array( 'jquery' ),
      COBLOCKS_VERSION,
      true
    );
  }

}
add_action( 'wp_enqueue_scripts', 'ds_load_coblocks_carousel_script' );

The light-box looks for one class on the parent div of the gallery, which is has-lightbox. You can add this under the "Advanced" tab on the sidebar.

Once you have done this, the lightbox can be used on any page with a gallery. Hopefully someone else can benefit from this!

It's worth noting that you can probably filter those classes and add the class automatically, but I wanted to avoid this so I had more control over which galleries it acts on.

richtabor commented 4 years ago

It be interesting to have a lightbox ToggleControl appended to the InspectorControls of the core image/gallery blocks, to give users the option to turn on lightbox for any image/gallery. 🤔

How possible is this @AnthonyLedesma?