I'm looking to insert data from another database into my posts, and thought of using shortcodes. An example post:

[imdb id="123" name] was born [imdb id="123" birthday] in [imdb id="123" birth_location].

I'd like to cache the results, and not need to run the shortcode actions anymore once it's been retrieved. Are there any good strategies for making this kind of thing efficient?


Either way you're going to need to store the data you retrieve from an external database, in your WordPress database, if you don't want to continually run the same query on your external database each time the page is accessed.

You can either store the data in your WordPress database using Custom Fields (post meta) using functions like add_post_meta and update_post_meta or via the use of the Transient API which will allow you to cache said data for a set period of time, have that data expire and be purged from your database and optionally have the query re-run on your external source.

Of course take into account your code needs to include conditional logic for which specifies;

if no transient data exists for the given data > fetch data from external source

Here is some example code of the Transient API in use;

// Get any existing copy of our transient data
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
     $special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' );
     set_transient( 'special_query_results', $special_query_results );

// Use the data like you would have normally...

In your instance replace the call to WP_Query to that with your external database source.

Your shortcode can then be a wrapper for which will allow you to insert data arbitrarily on a post by post basis, of course you'd need to create your shortcode too which I assume you have a rough idea of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.