Skip to content

Instantly share code, notes, and snippets.

@villesiltala
Last active December 8, 2021 00:07
Show Gist options
  • Save villesiltala/6ee4164795c03353b801155de0f31fd6 to your computer and use it in GitHub Desktop.
Save villesiltala/6ee4164795c03353b801155de0f31fd6 to your computer and use it in GitHub Desktop.
WordPress - Get a post by its post name (slug) and cache results.
<?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