Last active
December 8, 2021 00:07
-
-
Save villesiltala/6ee4164795c03353b801155de0f31fd6 to your computer and use it in GitHub Desktop.
WordPress - Get a post by its post name (slug) and cache results.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get a post object by its post name (slug). | |
* | |
* @param string $slug The post name value. | |
* @param string $post_type The post type to fetch from. Default: 'post'. | |
* | |
* @return \WP_Post|bool The post object if found, false if not. | |
*/ | |
function get_post_by_slug( $slug = '', $post_type = 'post' ) { | |
$cache = wp_cache_get( $post_type . '_by_slug_' . $slug ); | |
if ( $cache ) { | |
return $cache; | |
} | |
$posts = get_posts( | |
[ | |
'name' => $slug, | |
'post_type' => $post_type, | |
'posts_per_page' => 1, | |
'post_status' => 'publish', | |
] | |
); | |
if ( ! empty( $posts ) ) { | |
wp_cache_set( $post_type . '_by_slug_' . $slug, $posts[0] ); | |
return $posts[0]; | |
} | |
return false; | |
} | |
/** | |
* Clear the post by slug cache for a given post id before the new name is saved | |
* or the post is deleted from WordPress. | |
* | |
* @param int $post_id The WP post id. | |
*/ | |
function delete_post_by_slug_cache( $post_id ) { | |
$saved = get_post( $post_id ); | |
if ( $saved ) { | |
// Strip the trashed status that is inserted before any usable hook. | |
$post_name = str_replace( '__trashed', '', $saved->post_name ); | |
wp_cache_delete( $saved->post_type . '_by_slug_' . $post_name ); | |
} | |
} | |
add_action( 'pre_post_update', 'delete_post_by_slug_cache' ); | |
add_action( 'delete_post', 'delete_post_by_slug_cache' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment