How to delete a transient on post/page publish?

I have a transient set for a custom query. It expires in 30 days. But I also need it to expire once a new post/page is published. So that the new published post/page is available in that custom query. How to delete a transient on post/page publish?

How I set the transient:

// Get any existing copy of our transient data
   if ( false === ( $query = get_transient('d_results') ) ) {
    // It wasn't there, so regenerate the data and save the transient
    $randargs = array("post_type"=>"", "orderby"=>"", "order"=>"", "posts_per_page"=>-1);
    $query = new WP_Query($randargs);
    set_transient( 'd_results', $query, DAY_IN_SECONDS * 30);
   }

1 Answer
1

I am considering it for publication of a new post.

Add the below code in your active theme’s functions.php file.

function wpse_delete_query_transient( $post ) {
    // Deletes the transient when a new post is published
    delete_transient( 'd_results' );
}
add_action( 'new_to_publish', 'wpse_delete_query_transient' );

This will delete the transient every time a new post is published.

if you want to delete the transients on differrent post status transitions, you may like to look into the codex

Leave a Comment