WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

How to execute the gallery shortcode after any other content no matter where the shortcode is in the post HTML?


share|improve this question
up vote 0 down vote accepted

This is not bulletproof, but should work perfectly fine in most cases:

class WPSE_105676_Gallery_First {
    private static $_gallery = '',

    public static function gallery( $attr ) {
        self::$_gallery .= is_callable( self::$_handler ) ? call_user_func( self::$_handler, $attr ) : '';
        return '';

    public static function content( $text ) {
        $text .= self::$_gallery;
        self::$_gallery = '';
        return $text;

    public static function startup() {
        if ( ! isset( self::$_handler ) ) {
            if ( empty( $GLOBALS['shortcode_tags']['gallery'] ) || ! self::$_handler = $GLOBALS['shortcode_tags']['gallery'] )
                self::$_handler = 'gallery_shortcode';

            add_shortcode( 'gallery', array( __class__, 'gallery' ) );

        add_filter( 'the_content', array( __class__, 'content' ), 1000 );

add_action( 'init', array( 'WPSE_105676_Gallery_First', 'startup' ), 100 );

In layman's terms, in startup() we save the current shortcode handler for gallery (so this should also work with plugins & themes that override the default), then replace it with our own gallery() method. This is where we "capture" the gallery & return an empty string, so it no longer appears where the shortcode existed.

Out content() method is hooked to the_content on a low-priority filter to ensure it runs after all shortcode has been parsed, plus any other filters that might add their own content. This appends the captured gallery, resets the property, and returns the post content.

share|improve this answer
Thanks for your code and your explanations, but it doesn't work. Gallery stays on top. – Vincent Jul 8 '13 at 8:04
Works for me. Where have you placed the code? And are you referring to the front-end, or in the editor in the admin? – TheDeadMedic Jul 8 '13 at 9:28
You are right, sorry. With native gallery, it works. But not with my custom gallery add_shortcode( 'gallery', 'lilith_gallery' ); – Vincent Jul 8 '13 at 9:40
Is your custom function returning the code or echo'ing it? – TheDeadMedic Jul 8 '13 at 9:59
Right again! :) With "echo", it doesn't work. With "return", your code works perfectly. Thank you very much. – Vincent Jul 8 '13 at 17:10

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.