Tech Talk: using WordPress Gallery shortcode and ajax with no headaches

If you are a WordPress developer and ever needed to run a custom gallery shortcode using ajax (e.g. echo do_shortcode(' [customgallery]'); ), you probably got frustrated, because any custom gallery shortcode won’t work.

Well, i present you a workaround, if you don’t need multiple and different gallery html outputs. It will work if you only need to have ONE gallery and change the HTML code output of it.

We are working in a new website for one of 2ACES clients and we faced this problem. We also noticed that while the customized gallery shortcode we created ( echo do_shortcode(' [customgallery]'); ) failed when retrieved using ajax (it outputs the whole php code as a text string), the original code (echo do_shortcode('

');) keeps working fine when using ajax.

So, after struggling a litle bit, the solution came along and it is pretty simple: you need to unbind the original gallery function from the gallery shortcode and then bind your own gallery function to it.

Check the code below. Hopes it helps you.

Good luck.

//unbinds WordPress function in order to replace it with custom gallery code function
remove_shortcode('gallery', 'gallery_shortcode');
//binds new custom gallery code function
add_shortcode('gallery', 'gianfrancescobullogallery_shortcode');