invalidating transient cache..

In our assignment task we are creating a widget that queries the db, gets the movies and shows them as a list.

We are using transients to store the query results, so we don’t have to run another complex query on the db to get the data.

The expiration is set to 4 hours currently. What if new movies get added to db or existing movies meta data is updated.

We are using the meta query to get the posts by rating and release date.

This is the query I am using

$args   = array(
			'post_type' => 'rt-movie',
			// Using meta_key is necessary because the rating is stored as a meta data of movie post type.
			'meta_key'  => 'rt-movie-meta-basic-rating', // phpcs:ignore WordPress.DB.SlowDBQuery
			'orderby'   => 'meta_value_num',
			'order'     => 'DESC',
		);
		$query  = new WP_Query( $args );
		$movies = $query->posts;

And using the code to save the results in the transients, but if it is already saved then don’t run the query just return the results.

$movies = get_transient( 'mlb_top_rated_movies' );
		if ( $movies ) {
			return $movies;
		}
		....
		$query  = new WP_Query( $args );
		$movies = $query->posts;

		set_transient( 'mlb_top_rated_movies', $movies, HOUR_IN_SECONDS * 4 );
		return $movies;

Now, what happens if new movie is added or existing movies rating get’s decreased. We should not store the stale data and fetch the fresh data.

For that, I got this hook that we can use which will fire when post meta is updated.

		add_action('update_postmeta', array($this, 'delete_transients_on_meta_update') , 10, 4);

Now we can use this to check if the post meta is updated then we can just delete the transients instead of updating them with new data.

Out code will then add the data in the transients again.

/**
	 * Delete transients on meta update.
	 */
	public function delete_transients_on_meta_update($meta_id, $object_id, $meta_key, $meta_value ){

		if('rt-movie' !== get_post_type($object_id)){
			return;
		}

		if('rt-movie-meta-basic-rating' === $meta_key){

			delete_transient('mlb_top_rated_movies');
		}

	}


Note : I am still working on how to also hook into save_post and invalidate the transients when new movie is added.


User Roles and Capabilities

There are below rules by default in wordpress

  • Super Admin
  • Administrator
  • Editor
  • Author
  • Contributor
  • Subscriber

We can add our own roles too. For that we can use functions:-

  • add_role()
  • remove_role()

We can assign capabilities to this roles or remove them using

  • add_cap()
  • remove_cap()

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *