How to save new transients if query changes?

According to code in OP, the only thing that changes the result is the $tags variable.

In this case, the easiste way to do the trick is make the $tags part of the transient name.

function get_posts_by_tags($tags){

    $transient="rest-posts-" . md5(serialize($tags));

    if(false === ($result = get_transient($transient))) {

          // the rest of yout function here ...

          if (!is_wp_error($data)){
             $result = json_decode( $data );

             set_transient($transient, $result, 24 * HOUR_IN_SECONDS);
          }   
    }

    return $result;
}

So for every $tags there is a transient.

If different pages result in same $tags they will query (and store) same transient and everything should work as expected.

Leave a Comment