6

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>
             </div>
      </section>
 </div>
  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?

1
  • Related question with different solutions.
    – kaiser
    Commented Apr 7, 2014 at 8:21

1 Answer 1

6

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.

Prototype

<?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 );
    }
}
3
  • 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 M
    Commented May 29, 2012 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.
    – fuxia
    Commented May 29, 2012 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
    Commented Nov 6, 2013 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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