This small function allows you to display most popular images from the past week and cache the results for 24 hours.
Note that you need to change your post_type
, if it’s different than image
.
This feature works with ImagePress version 7 or higher.
function feed_most_viewed($count) {
// Get transient
$is = get_transient('popular-images');
if (false === ($the_query = get_transient('popular-images'))) {
$args = array(
'post_type' => 'image',
'posts_per_page' => $count,
'orderby' => 'meta_value_num',
'meta_key' => 'post_views_count',
'meta_query' => array(
array(
'key' => 'post_views_count',
'type' => 'numeric'
)
),
'date_query' => array(
array(
'after' => '1 week ago'
)
),
);
$is = get_posts($args);
// Set transient, and expire after 24 hours
set_transient('popular-images', $is, 1 * DAY_IN_SECONDS);
}
if ($is) {
$display = '<ul>';
foreach ($is as $i) {
$post_thumbnail_id = get_post_thumbnail_id($i->ID);
$postAuthor = $i->post_author;
if (has_post_thumbnail($i->ID)) {
$display .= '<li>' . do_shortcode('') . '<a href="' . get_permalink($i->ID) . '" class="regular-link"><b>' . get_the_title($i->ID) . '</b></a><br><small>by <a href="' . get_author_posts_url($postAuthor) . '" class="regular-link">' . get_the_author_meta('display_name', $postAuthor) . '</a></small><br><br><a href="' . get_permalink($i->ID) . '">' . wp_get_attachment_image($post_thumbnail_id, 'thumbnail') . '</a>
</li>';
}
}
$display .= '</ul>';
}
return $display;
}
Use this in your theme’s functions.php
file or in a custom plugin.