vendredi 22 juillet 2016

Wordpress random image header with Wordfence caching

Q: How can I serve an image that is randomized every time a user visits/refreshes a page, via a method that caching doesn't break?

I've coded the following in my Wordpress site's page.php:

<?php if (has_post_thumbnail( $posts_page_id ) ):  // part 1  ?>

    <div class="featured-img" style="background-image:url(<?php echo $thumb_url_splash ?>);"></div>

<?php else:  // part 2

    $gallery = get_field('header_images', 530);
    $rand = array_rand($gallery, 1);
    <div class="featured-img" style="background-image: url('<?php echo $gallery[$rand]['url']; ?>');"></div>

<?php endif; ?>

  1. Check if the page has a featured image. If it does, display it.
  2. If not, display a random image every time the page is loaded (from an ACF Pro-generated gallery on another page with ID of 530).

This works fine until I turn on Wordfence's caching -- then the randomization is cached along with the rest of page, and the page displays the same image until the next time the cache is cleared.

(Wordfence has a doNotCache function but calling it prevents the entire page from being cached; since I'm using this header image code in 90% of pages, using doNotCache would basically turn caching off on 90% of pages, defeating the point of enabling caching!)

I'm good at HTML/CSS but less experienced at PHP/JS. I've heard that JS won't be cached by Wordfence, and that one solution might be passing the PHP array to JS via json_encode, but I have no idea how to make that work or if it's the best solution to this problem.

Apologies for my ignorance, hopefully my explanation is clear. Thanks!




Aucun commentaire:

Enregistrer un commentaire