Last active
May 18, 2023 17:35
-
-
Save michael-sumner/1bb6eb966105ae077b56c709530be953 to your computer and use it in GitHub Desktop.
get_recent_post_ids() Gets an array of recent post IDs based on the number of posts. Contains caching mechanism for high-performance. ⚡️
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 | |
/** | |
* Gets an array of recent post IDs based on the number of posts. | |
* | |
* @param int $num_posts The number of recent posts to retrieve. Defaults to 6. | |
* @param int $expiration_time The expiration time for the cache, in seconds. Defaults to 1 hour. | |
* | |
* @return array An array of recent post IDs. | |
*/ | |
function get_recent_post_ids( int $num_posts = 6, int $expiration_time = 1 * HOUR_IN_SECONDS ): array { | |
$cache_key = 'recent_posts_' . $num_posts; | |
$cached_post_ids = get_transient( $cache_key ); | |
if ( $cached_post_ids !== false ) { | |
return $cached_post_ids; | |
} | |
$args = array( | |
'numberposts' => $num_posts, | |
'fields' => 'ids', | |
'suppress_filters' => false, | |
); | |
// phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.get_posts_get_posts | |
$recent_post_ids = get_posts( $args ); | |
set_transient( $cache_key, $recent_post_ids, $expiration_time ); | |
return $recent_post_ids; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment