Skip to content

Commit

Permalink
in get_most_viewed_posts_ids; cache results that return an empty set …
Browse files Browse the repository at this point in the history
…and prefix cache key with unique identifier (vs. just md5 of args)
  • Loading branch information
dannyvankooten committed Feb 21, 2025
1 parent 50c5e1a commit 14c5994
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ function get_settings(): array
function get_most_viewed_post_ids(array $args)
{
global $wpdb;
$cache_key = md5(serialize($args));
$args_hash = md5(serialize($args));
$cache_key = "ka_most_viewed_{$args_hash}";
$post_ids = wp_cache_get($cache_key, 'koko-analytics');
if (!$post_ids) {

if (false === $post_ids) {
$args = array_merge([
'number' => 5,
'post_type' => 'post',
Expand All @@ -46,22 +48,21 @@ function get_most_viewed_post_ids(array $args)
$args['post_type'] = is_array($args['post_type']) ? $args['post_type'] : explode(',', $args['post_type']);
$args['post_type'] = array_map('trim', $args['post_type']);

$start_date_str = $args['days'] === 0 ? 'today midnight' : "-{$args['days']} days";
$start_date = create_local_datetime($start_date_str)->format('Y-m-d');
$end_date = create_local_datetime('tomorrow midnight')->format('Y-m-d');
$timezone = wp_timezone();
$date_start = new \DateTimeImmutable($args['days'] === 0 ? 'today midnight' : "-{$args['days']} days", $timezone);
$date_end = new \DateTimeImmutable('tomorrow, midnight', $timezone);

// build query
$sql_params = [
get_option('page_on_front', 0),
$start_date,
$end_date,
$date_start->format('Y-m-d'),
$date_end->format('Y-m-d'),
...$args['post_type'],
$args['number'] * $args['paged'],
$args['number'],
];

$post_types_placeholder = rtrim(str_repeat('%s,', count($args['post_type'])), ',');

$sql = $wpdb->prepare("SELECT p.id, SUM(pageviews) AS pageviews
FROM {$wpdb->prefix}koko_analytics_post_stats s
JOIN {$wpdb->posts} p ON s.id = p.id
Expand All @@ -71,10 +72,6 @@ function get_most_viewed_post_ids(array $args)
LIMIT %d, %d", $sql_params);

$results = $wpdb->get_results($sql);
if (empty($results)) {
return [];
}

$post_ids = array_map(function ($r) {
return $r->id;
}, $results);
Expand Down Expand Up @@ -106,8 +103,10 @@ function get_most_viewed_posts($args = []): array
// By default, WP_Query only returns "post" types
// Without this argument, this function would not return any page types
'post_type' => 'any',

// Prevent sticky post from always being included
'ignore_sticky_posts' => true,

// Excludes SQL_CALC_FOUND_ROWS from the query (tiny performance gain)
'no_found_rows' => true,
];
Expand Down

0 comments on commit 14c5994

Please # to comment.