What would be the correct way to assign a different name to each transient for each instance of a plugin used as a widget or shortcode?
2 Answers
Transients have practical limitation on key length (45 symbols or something like that), so using dynamic keys tends to come with risk of ending up with keys too long and having it break down.
One of common practices is to form unique string (for example combination of plugin name and type of data being saved, etc) and hash it with md5()
to use as transient key of fixed predictable length.
For clarity could use plugins name to prefix md5 hash instead, so it's clear where transient comes from, when seeing it in database.
The key length limit that Rarst mention was extended from 45
characters to 172
characters (see https://core.trac.wordpress.org/ticket/13310), so it's no longer a concern in most cases.
Generally, you can just create a name like {plugin prefix}-{name of transient}-{unique id}
; e.g., abcd-remote-api-results-15
, or abcd-expensive-query-results-foo
The unique ID will be generated differently based on the context. Widgets have a instance ID associated with them ($this->number
), so you can use that. Shortcodes have a unique combination of parameters, so you can hash that (md5( serialize( $attributes ) )
.