Using preg_replace to separate gallery from the_content?

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:

Read More
 <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?

Related posts

Leave a Reply

1 comment

  1. 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 );
        }
    }