Forked from klihelp/kli_gutenberg_gallery_fix.php
Last active
December 22, 2020 16:59
-
-
Save DrYurets/f7178889d71a6d352b915f04f97c4088 to your computer and use it in GitHub Desktop.
Replace Gutenberg gallery block with the gallery shortcode.
This file contains hidden or 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 | |
/** | |
* WordPress Gutenberg gallery block fix to the gallery shortcode. | |
*/ | |
/** | |
* Replace Gutenberg gallery block with the gallery shortcode. | |
* Tested until Gutenberg 2.4 | |
* | |
* @param $the_content | |
* | |
* @return string | |
* | |
*/ | |
if ( ! is_admin() ) { | |
add_filter('the_content', function($content) { | |
if ( ! is_main_query() ) { | |
return $content; | |
} | |
// Find gallery blocks | |
$regexp = "<ul\s[^>]*wp-block-gallery[^>]*>(.*)<\/ul>"; | |
if ( preg_match_all("/$regexp/imsU", $content, $matches, PREG_PATTERN_ORDER) ) { | |
$updated = false; | |
foreach($matches[0] as $key => $match) { | |
if ( preg_match_all('/\sdata-id="(.*)"/imsU', $match, $match_ids, PREG_PATTERN_ORDER) ) { | |
$matches[1][$key] = '[gallery ids="'. implode(',', $match_ids[1]) .'"]'; | |
$updated = true; | |
} | |
} | |
if ($updated) { | |
foreach ($match_ids[1] as $key => $img) { | |
$img_full_href = wp_get_attachment_image_src($img, 'full')[0]; | |
$img_thmb_href = wp_get_attachment_image_src($img, 'medium')[0]; | |
$content = str_replace('src="'.$img_full_href, 'src="'.$img_thmb_href, $content); | |
} | |
} | |
} | |
return $content; | |
}, 9); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment