JCHASE11
JCHASE11

Reputation: 3941

Multiple Image Sliders on one page created with php loop

I am using wordpress to loop through my posts and return 5 images from each post. I am then loading these 5 images into a slider. I am looping through 10 pages, which returns a total of 10 sliders on one page. Potentially, the admin of the site can create an infinite amount of posts (portfolio items), yielding an infinite amount of sliders (10 on each page, with pagination).

Many jquery slider plugins allow for multiple sliders on one page, but they all require that you call them with a unique selector. For example, the first 5 sliders would be called like this:

 $("#portfolio-slider-1").bxSlider();
 $("#portfolio-slider-2").bxSlider();
 $("#portfolio-slider-3").bxSlider();
 $("#portfolio-slider-4").bxSlider();
 $("#portfolio-slider-5").bxSlider();

If I had 300 sliders, there would be 300 calls...now doesnt that seem unnecessary? Especially with wordpress having one common header/footer.php - it would make these calls on every page (even the pages that dont have these slider containers). Totally unnecessary.

And the other problem is assigning wordpress's dynamically generated posts (portfolio item) with a unique id. Because wordpress is looping through the posts, it cannot give each post a div ID of 1, then 2, then 3, and so on. Wordpress would give each post a class of .portfolio-slider which would not work with a jquery slider plugin.

That just doesnt seem right. But then again, I cant think of a good solution that would allow for many sliders on one page, with a common class name. I have tried that with so many plugins and it just doesnt work. They all require unique IDs! So I suppose my question is, how do I go about adding many image sliders on one page that allows for the dynamic generation of items (must be class name, not ID)?

Upvotes: 0

Views: 2957

Answers (1)

jmoerdyk
jmoerdyk

Reputation: 5526

Your should be able to condense your multiple .bxSlider() calls with this:

$('[id^="portfolio-slider-"]').each(function(){
    $(this).bxSlider();
});

Which basically translates to: for each element that has an id that starts with "portfolio-slider-" call the .bxSlider() on it.

To use the .portfolio-slider class instead, and apply the .bxSlider() to each one separately:

$('.portfolio-slider').each(function(){
    $(this).bxSlider();
});

The key here is using the each, so the function is applied to each element separately instead of the collection of all elements.

Upvotes: 4

Related Questions