0

I've installed the Fancybox Plugin for Wordpress on a website. In normal pages, wheneaver I insert the Wordpress shortcode gallery or images, it works just fine.

But I have some pages where posts are loaded through an ajax function.

I know that, normally, the Fancybox Plugin scans the page for every image and then creates an attribute "rel='fancybox' on each of them. Therefore, if the page is already loaded and I add some content to it with AJAX, I don't expect the plugin to work, since it is triggered with de jQuery(document).ready statement.

How can I solve this issue? I thought of putting a str_replace function on the PHP function that is triggered by the AJAX call, like this:

$content = get_the_content(); 

// this will get the post_content and store it in the $content variable

$content = apply_filters('the_content', $content);

// this will make wordpress execute the shortcodes on the string $content

$content = str_replace('<a ', '<a rel="fancybox" ', $content);

// this SHOULD make the fancybox appear.

How can I solve this issue? Thanks a lot.

  • This is probably a problem with your JS (the fancybox initialization has to be triggered again after the AJAX has updated the page), so you will have to provide us with the JS you are using a. to build the fancybox functionality and b. to update the DOM. – m90 Mar 27 '12 at 07:31

1 Answers1

0

Many things to consider here.

this

$content = str_replace('<a ', '<a rel="fancybox" ', $content);

won't fire fancybox but bind the <a rel="fancybox tag to fancybox IF (and only if) a custom script like this exist

$("a[rel='fancybox']").fancybox();

however, you are adding this element on the fly (or using the replace method to add the rel attribute), which it means that it didn't exist in the DOM at the time the fancybox plugin was loaded.

If you are using fancybox v1.3.4 or below, this (these) version(s) doesn't (don't) support dynamically added elements so none of the above will (ever) work.

As a workaround, you may try to identify the parent container and apply the .on() method as described here.

You may need to tweak the script to fit to your needs like

$("#container").on("focusin", function(){
 $("a[rel='fancybox']").fancybox({ ......

Last note: fancybox v2.x already supports both existing and dynamically added elements.

Community
  • 1
  • 1
JFK
  • 40,963
  • 31
  • 133
  • 306