What is the appropriate approach to sharing data between multiple short codes in WordPress?

I have created a set of short codes to allow users to lay out the display of my custom post type (herein abbreviated CPT) within their own page.

For brevity, lets assume we’re only looking at these three, which I’ve generalized to be more clear:
[CPT_title], [CPT_body], and [CPT_taxonomy]

Read More

Each grabs the post ID from the $_GET, creates a WP_query, and displays the relevant data from the database.

Now, obviously it’s poor programming to query the same data again and again for each shortcode, so I’d like to share this query data between them.

What’s the most appropriate way to do so?

Related posts

1 comment

  1. You could make use of a static variable as a sort of “runtime cache” within your function to avoid duplicate database calls. You just need to ensure you build your array/object storage to appropriately deal with the subsequent calls for different post ID’s (ie Post ID might be an index in your array)

    function getStuffCached()
    {
      static $cache = null;
      if( $cache === null )
      {
        $cache = getStuffFromDatabase();
      }      
      return $cache;
    }
    

    -or-

    function getStuffCached( $index )
    {
      static $cache = array();
      $postID = get_the_ID();
      if( isset( $cache[ $postID ] ) === false )
      {
        $cache[ $postID ] = getStuffFromDatabaseAsArray();
      }
      return ( isset( $cache[ $postID ][ $index ] ) ) ? $cache[ $postID ][ $index ] : null;
    }
    

Comments are closed.