Using preg_replace to separate gallery from the_content?

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

Leave a Comment

error code: 523