Random String Shortcode To Fix A PDF Caching Problem

On my church’s website, we post links to our missionaries’ newsletters as PDF files. We have a problem with browsers caching the older newsletters so even though a new file is on the server, the older file appears in the browsers. Not even clearing the cache seems to work. Adding to the problem is when Cloudflare.com caches the file, so I have to log in and delete the cache there.

One solution is to rename the PDF file and then change the link on the site every time. But we like to be lazy efficient around here, so I came up with a shortcode function that inserts a random string.

Adding a question mark and a random string to the end of the link so the browser would ¬†fetch the latest version of the file rather than get the cached version in their browser’s history.

So for each newsletter link, I went into HTML mode and added


to the end of the link’s href attribute. So

<a href="http://domain.com/newsletter.pdf">Newsletter</a>


<a href="http://domain.com/newsletter.pdf?[randomstring]">Newsletter</a>

and when the post/page is rendered in a browser, [randomstring] would be replaced by a random string of 5 characters. 5 is the default, but the length can be changed by setting the “length” attribute in the shortcode like this:

[randomstring length=10]

Here is the code you need to add to your function.php file in your WordPress theme to make this work.

 random string function
if (!function_exists("random_string")) {
function random_string($atts, $content = null){
 'length' => '5' 
 $l = $length;
 Credit: This section of code by "kriskra at gmail dot com"
 $c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";
 for(;$l > 0;$l--) $s .= $c{rand(0,strlen($c))};
 return str_shuffle($s);

add_shortcode('randomstring', 'random_string');

I decided to keep this simple by not letting the function add the question mark, because a need may arise where you need to use an ampersand instead or perhaps nothing at all.


One thought on “Random String Shortcode To Fix A PDF Caching Problem

  1. Thanks for this. I’ve encountered the catching problem myself when uploading new versions of my resume, regardless if it was PDF, doc, or txt file.

Comments are closed.