Add_shortcode not working

Today I had a little of a trouble trying to replace the default gallery shortcode in WordPress. I finally found out that there was nothing really wrong with the code, but I had to work around the way I had to register it.

If you too experience that your efforts to employ the add_shortcode() feature fail short, you may want to try the way I am suggesting here.

My goal was to replace the original gallery shortcode, so that to output a more appropriate mark up in a custom theme. Doing as showed here below did in fact removed the default shortcode but also left me with nothing.

remove_shortcode('gallery', 'gallery_shortcode');
add_shortcode( 'gallery', ‘my_gallery_shortcode' );
function my_gallery_shortcode( $attr ) {
  // the new gallery logic here
}

The first line did actually work. Which resulted in the mere text output [gallery] where I was expecting the new gallery logic to take place. So I was getting just this.

[gallery]

Pretty poor, right?

Try this one, instead.

remove_shortcode('gallery', 'gallery_shortcode');
add_action('init', 'add_my_gallery_shortcode’, 99);
function add_my_gallery_shortcode() {
  add_shortcode( 'gallery', ‘my_gallery_shortcode’);
}
function my_gallery_shortcode( $attr ) {
  // the new gallery logic here
}

Apparently, shortcodes need to be registered at the “init” level. Otherwise WordPress does not receive them correctly, and therefore does not execute them as you want it to.

If you wonder what the 99 is for at the end second line, that is the priority given to the instruction. WordPress, will order all the functions associated with a particular action (in this case “init”) depending by their numerical priority.

Shortcodes do not need to have a high priority. In fact for the most you may want them to be registered at the very end.

Hopefully this will help. Feel free to add any comment or question on the topic.

Further resources