Is it possible to remove gallery from content but in its place do get_template_part('content-gallery');
?
I have this piece of code which removes gallery from post but I am inserting content-gallery.php which grabs and formats gallery the way I wanted to. This works nice but gallery is inserted at the end of the post what is the problem, it needs to be inserted in whatever position it is in post. I just want a quick fix.
functions.php - removes gallery
add_filter('the_content', 'remove_gallery');
function remove_gallery($content) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false)
return substr_replace( $content, '', $pos, strlen($shortcode[0]) );
}
}
}
return $content;
}
content-gallery.php - manual gallery - call images and format them easily
$gallery = get_post_gallery( get_the_ID(), false );
$gallery_attachment_ids = explode( ',', $gallery['ids'] );
$img_attribs = wp_get_attachment_image_src($gallery_attachment_ids[0], 'gallery_main' ); // returns an array
if( $img_attribs ) :
foreach($gallery_attachment_ids as $id) :
$img = wp_get_attachment_image_src($id, 'gallery_thumb' );
$img_full = wp_get_attachment_image_src($id, 'gallery_main' );
$img_alt = get_post_meta(get_the_ID(), '_wp_attachment_image_alt', true);
?>
<div class="item">
<img class="thumb img-responsive" data-url="<?php echo $img_full[0]; ?>" id="<?php the_ID(); ?>" src="<?php echo $img[0]; ?>" alt="<?php echo $img_alt; ?>" title="<?php echo $img_alt; ?>" />
</div>
<?php endforeach; ?>
This is in page.php
(I would need to remove manual calling for get_template_part()
and call it inside filter function.
<?php the_content(); ?>
<?php get_template_part('content-gallery'); ?>
EDIT
Full filter function
add_filter('the_content', 'remove_gallery');
function remove_gallery($content) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false) {
ob_start;
get_template_part('content-gallery.php');
$contentgallery = ob_get_contents();
ob_end_clean();
return substr_replace( $content, $contentgallery, $pos, strlen($shortcode[0]) );
}
}
}
}
return $content;
}
get_gemplate_part()
is a function that echoes its output. It doesn't return any variable you can process within a search and replace logic. That's why you can't use it inside a filter that way without output buffering, which is not very performant. I would advice you to rethink the whole approach. Can't you use thepost_gallery
filter to apply your html instead of loading an external template? It seems more reusable and not theme dependant.