Skip to content

Instantly share code, notes, and snippets.

@lukecarbis
Created April 22, 2019 22:58
Show Gist options
  • Save lukecarbis/031096956421e0fa3b8389dc16eb6b6a to your computer and use it in GitHub Desktop.
Save lukecarbis/031096956421e0fa3b8389dc16eb6b6a to your computer and use it in GitHub Desktop.
<?php
/**
* Custom block to create a gallery based on image folder in uploads.
*
* @package Block Lab
*/
?>
<div class="singlepost__media__image has-pswp">
<?php
$home_url = home_url() . '/wp-content/uploads' . block_value( 'imagefolder' );
$upload_dir = wp_upload_dir();
$image_folder = $upload_dir['basedir'] . block_value( 'imagefolder' );
$files = glob( $image_folder . '/*.jpg' );
foreach ( $files as $image_name ) {
if ( ! $files ) {
continue;
}
$file = $home_url . basename( $image_name );
?>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="<?php echo esc_attr( $file ); ?>" itemprop="contentUrl" class="singlepost__media__image__link">
<img class="lazy" data-object-fit="cover" alt="<?php echo esc_attr( $file ); ?>" src="<?php echo esc_attr( $file ); ?>">
</a>
</figure>
<?php
}
?>
</div>
@lukecarbis
Copy link
Author

This is a response to this support ticket: https://wordpress.org/support/topic/block-preview-not-working/

Edit Block

Block in Post

A few notes on this approach:

  1. It's very important that the folder name provided in the block's text field contains a slash at the beginning and at the end. Ideally, we should setup some code logic in the template to add the slash if it doesn't exist.
  2. In the example given in the support ticket, the $home_url was set to home_url() . '/website/wp-content/uploads'. I'm not sure why website would be a part of that URL, since if WordPress was installed in a subdirectory, that should still be included in the result of home_url()
  3. Notice that the <div> is output whether there are any results or not. It's important that we return something.

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