Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stores transient in post meta
<?php
/***
Stores persisent data as post meta instead of using Transient API
@param $post_id int post ID to store post meta for
@parm $meta_key str "transient" name
@param $update_func str function to update the meta key with a new value
@param $expiration time when value should expire
return $value array stored value or updated value
***/
function yournamespace_get_post_transient( $post_id, $meta_key, $update_func, $expiration = null ) {
if ( null == $expiration ) {
$expiration = strtotime( '+7 days' );
}
//uncomment and request endpoint to clear cache:
//delete_post_meta($post_id, $meta_key);
$current_value = get_post_meta( $post_id, $meta_key, true );
//this is the "cached" value
//if the meta value is in the right format and it's not expired, we return it and we are done
if ( is_array( $current_value ) && $current_value['expiration'] > time() ) {
return $current_value['data'];
}
//either expired or didn't exist so let's call our "update" function
$new_data = call_user_func( $update_func, $post_id );
//store output in an array so that we can check expiration later
$value = array(
'expiration' => $expiration,
'data' => $new_data
);
//save this new value to post meta
update_post_meta( $post_id, $meta_key, $new_value );
//return just the data for use in the endpoint
return $value['data'];
}
/***
Update function example - this is the data you're actually using in your endpoint or custom field
@param $post_id int post ID to store post meta for
return $meta array Your value
***/
function yournamespace_get_custom_meta( $post_id ) {
$test_meta_value = get_post_meta('test_meta_value', $post_id);
$some_other_thing = get_post_meta('some_other_thing', $post_id);
$expensive = maybe_a_really_crazy_query($post_id);
$meta = array(
'test_thing' => $test_meta_value,
'some_thing' => $some_other_thing,
'expensive_thing' => $expensive
);
return $meta;
}
/***
Clear yc_collection_meta post_meta transient on post save/update
***/
function yournamespace_delete_meta_transient( $post_id, $post, $update ) {
delete_post_meta( $post_id, 'yc_collection_meta' );
yc_get_post_transient( $post_id, 'yc_collection_meta', 'yc_get_collection_meta' );
}
add_action( 'save_post_{your_post_type}', 'yournamespace_delete_meta_transient', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.