I'm using gutenberg gallery block inside a post and I'm trying to create a button which contains all of the image ids in the gallery block as html data attributes such that later when I output the content to the page I can have access to those ids using javascript
. Basically I'm trying to create a lightbox feature for a custom post type.
The problem is that I can't get access to the gutenberg gallery block data.
Here's my code
while ($custom_post_type->have_posts()) {
$custom_post_type->the_post();
$gallery = get_post_gallery(get_the_id(), false);
$ids = explode(",", $gallery['ids']);
}
And here's that button with html data attributes
<button class="gallery"
<?php
for ($i = 0; $i < count($ids); $i++) {
$img_link = wp_get_attachment_image_url($ids[$i], 'full');
echo "data-img-" . $i . " = " . $img_link . " ";
}?>
>
Light-box
</button>
But it does not work, $ids
is empty. It prints out this
<button class="gallery">Light-box</button>
Thanks for your help!
I'm using wordpress blocks on the post page, I'm not quite certain how they have been generated, but they work out of the box.
"it does not work,
$ids
is empty."
That block is one of the default wordpress blocks, aka "core blocks". In order to have access to its data you would need to use parse_blocks
function not get_post_gallery
. That's why your variable is empty.
So the overall workflow to get what you're looking for would be:
has_block
function. has_block
Docs
parse_blocks
function. parse_blocks
Docs
parse_blocks
will return an array of all blocks used in your post, so loop through them and see which one is called "core/gallery"
."core/gallery"
block has "attributes"
and "ids"
for each image you've added in the admin panel."ids"
, you should be able to create your custom button and image links using wp_get_attachment_image_url
function. wp_get_attachment_image_url
Docs
As a POC:
Please see the following code:
if (has_block("gallery", get_the_content()))
{
$post_blocks = parse_blocks(get_the_content());
foreach ($post_blocks as $post_block)
{
if ("core/gallery" == $post_block["blockName"])
{
$ids = $post_block["attrs"]["ids"];
}
}
}
And this is the button:
<button class="gallery"
<?php
for ($i = 0; $i < count($ids); $i++) {
$img_link = wp_get_attachment_image_url($ids[$i], "full");
echo "data-img-" . $i . " = " . $img_link . " ";
}
?>
>
Light Box
</button>
Which will return:
Note:
get_the_content
function, assuming that you're in the loop based on the code you provided in your question. If you're not in the loop or you would need to use the code outside of the loop you could use global $post; $post->post_content;
instead.This answer has been tested on wordpress 5.8
and works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With