Created
November 25, 2024 13:38
-
-
Save wpmark/2bd9764bae3d2e283c6aaf58a9d0b0ea to your computer and use it in GitHub Desktop.
Add image and total image count to the WordPress Gallery block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add current image and total image count attrs to the gallery block. | |
* | |
* @param string $block_content The block content. | |
* @param array $block The block type. | |
* @param array $instance The block attributes. | |
* | |
* @return string The modified block content. | |
*/ | |
function hd_utility_edit_gallery_markup( $block_content, $block, $instance ) { | |
// create a new instance of the WP_HTML_Tag_Processor class. | |
$tags = new WP_HTML_Tag_Processor( $block_content ); | |
// set figure counter. | |
$count = 0; | |
// loop through each image block. | |
while ( $tags->next_tag( [ 'class_name' => 'wp-block-image' ] ) ) { | |
// increment the count. | |
$count++; | |
// add an attribute for the current image count. | |
$tags->set_attribute( 'data-image-current', $count ); | |
// set the total images count attribute. | |
$tags->set_attribute( 'data-image-total', count( $block['innerBlocks'] ) ); | |
} | |
// save the manipulated HTML back to the block content. | |
$block_content = $tags->get_updated_html(); | |
// return the block content. | |
return $block_content; | |
} | |
add_filter( 'render_block_core/gallery', 'hd_utility_edit_gallery_markup', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment