WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In a Wordpress theme, I need to separate a gallery from the rest of the_content. I think one could do that with get_the_content and preg_replace but it's a little beyond my skill level how to actually implement the solution.

Here are the specifics. There's a gallery that looks like this:

 <div class="gallery">
      <section class="clearfix">
            <div class="gallery-row">
         some <figures>
  the rest of the content

Is there some way I could get that gallery into a variable and put all the rest of the content in another variable.

Then I could just echo the variables wherever I wanted, right?

share|improve this question
Related question with different solutions. – kaiser Apr 7 '14 at 8:21

The easiest way to do that is to hijack the gallery shortcode (no extra regex needed), store it somewhere and add it to the end.


<?php # -*- coding: utf-8 -*-
 * Plugin Name: T5 Move Galleries To End Of Content
add_action( 'after_setup_theme', array ( 'T5_Move_Galleries', 'init' ) );

class T5_Move_Galleries
    public static $galleries = array();

     * Re-order gallery shortcodes and register the content filter.
    public static function init()
        remove_shortcode( 'gallery', 'gallery_shortcode' );
        add_shortcode( 'gallery', array ( __CLASS__, 'catch_gallery' ) );
        // Note the priority: This must run after the shortcode parser.
        add_filter( 'the_content', array ( __CLASS__, 'print_galleries' ), 100 );

     * Collect the gallery output. Stored in self::$galleries.
     * @param array $attr
    public static function catch_gallery( $attr )
        self::$galleries[] = gallery_shortcode( $attr );

     * Append the collected galleries to the content.
     * @param  string $content
     * @return string
    public static function print_galleries( $content )
        return $content . implode( '', self::$galleries );
share|improve this answer
What I need, though, is to put the gallery (and content) in a string I can then echo anywhere in the loop. In this case, I want to echo the gallery, then the title and some meta content, then the_content. – Josh May 29 '12 at 22:40
Hm … that's tricky because the shortcode is applied to the_content. You could just change the method print_galleries() to return the desired result. – toscho May 29 '12 at 22:48
I stumbled upon a way to separate gallery and content, it will only use the first instance of the gallery shortcode though. wordpress.stackexchange.com/questions/121489/… – Howdy_McGee Nov 6 '13 at 23:04

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.