I’m trying to set user meta based on queries. Basically, things like IF the query returns true, set this or if not, set this (or don’t set it, if it is true). This works great but the problem is I currently make the call EVERTYIME to check true or false which I know is bad and unnecessary especially for the types of queries I am making (if it is true, it will ALWAYS stay true after that).
So, how should I cache these requests? Should I set it with the WordPress Transient API or should I do a cron job to run every X hours and then “update_user_meta” based on the result?
I am just a bit lost on either approach and need some guidance on the right path for this. Thanks!
Although both of your options (that is, using transients or using a cron job) are viable, I’m a fan of using transients unless the dataset is exceptionally large or if there is some need to automate the process.
Without seeing much of your current code, it’s difficult to give a working example. Nonetheless, if you end up going the route of transients, I’d recommend something like this:
Generally speaking, the code above will do this:
Check the cache to see if the value exists. If the value is found, then nothing else will execute; however, the cache will expire after 24 hours so eventually, it will return null.
If the value is not in the cache, then we check the user’s meta data. If it’s there, we use it; otherwise, we’ll manually create it then update the user meta. If the user meta has never been created, WordPress will add it when running the
update_user_meta
function.Finally, we unconditionally update the cache either with the data in the meta table or with what was manually created.
The only problem with the above code is that if the user meta is never be updated because the above function uses what’s there and only updates it if it’s null. To mitigate this, I’d expect:
For example:
Manny’s comment also provides some good insight so don’t ignore the answers on that particular question either.
There were some good answers from when I asked a similar question a few months back here