0WordPress Local Gravatar cache

I like to have avatars shown for people who com­ment on my blog. Word­Press sup­ports the gravatar ser­vice nat­ively so enabling this is very easy. How­ever it comes with a cost — access­ing extern­al files from anoth­er domain adds lots of extra load time in the form of new DNS look­ups, new SSL con­nec­tions to make, etc. Would­n’t it be nice to have gravatars stored loc­ally and served from your own serv­er. Well that’s what I’ve been doing for some time now, if you’d like to know how, read on…

In case you’re still won­der­ing just why you’d want to do this, let me offer a few more bene­fits — images served loc­ally can be com­pressed before serving them, for example ‑all my images are con­ver­ted into webp ver­sions, and any browser which sup­ports webp gets the webp ver­sion. This is in addi­tion to the reduc­tion from not hav­ing to con­nect to an extern­al serv­er. The loc­al resources can also have a cach­ing head­er set on them so that browsers will cache them. Gravatar does­n’t provide for a very long cache time.

I have cre­ated 3 cus­tom func­tions, which I simply place in my theme’s functions.php. The first is a cus­tom fil­ter for the nat­ive word­press get_avatar(). The second grabs avatars from gravatar and google when called upon, and the third cre­ates a daily cronjob which refreshes the gravatars — in case they’ve been changed, or a pre­vi­ously unavail­able one is now available.

You will need to do a little bit of tinker­ing to make it com­pat­ible with your theme — I use the “bones” frame­work as you’ll notice in the 3rd func­tion I’ve reused some code that it provided. You will also need to cre­ate, or cus­tom­ise the path to store the gravatars, which in my case are stored in the theme folder in the sub­path “/library/images/gravatars/”

Think we've missed something? Let us know by commenting below. If you would like to subscribe please use the subscribe link on the menu at the top right. You can also share this with your friends by using the social links below. Cheers.

Leave a Reply