Skip to content

Instantly share code, notes, and snippets.

@jeherve

jeherve/plugin.php

Last active Jun 6, 2016
Embed
What would you like to do?
Create an ordered list of popular posts, using Jetpack's Site Stats. See wordpress.org/support/topic/2883315
<?php
/**
* Create an ordered list of popular posts, using Jetpack's Site Stats.
*
* @see wordpress.org/support/topic/2883315
*/
function jeherve_new_top_posts() {
if ( ! function_exists( 'stats_get_csv' ) ) {
return;
}
// Look for data in our transient. If nothing, let's get a list of posts to display
$data_from_cache = get_transient( 'jeherve_top_list' );
if ( false === $data_from_cache ) {
$popular = stats_get_csv( 'postviews', array( 'days' => 7, 'limit' => 10 ) );
// Let's cache those results for an hour.
set_transient( 'jeherve_top_list', $popular, 60 * MINUTE_IN_SECONDS );
} else {
$popular = $data_from_cache;
}
// If there are no popular posts, let's stop here.
if ( ! $popular ) {
return;
}
// Let's build an array of post IDs.
$post_ids = array_filter( wp_list_pluck( $popular, 'post_id' ) );
if ( ! $post_ids ) {
return;
}
// Open our ordered list.
$list = '<ol>';
// Now let's create a loop and display posts.
foreach ( $post_ids as $post_id ) {
// Let's remove all post IDs that do not use the Recipes category.
if ( ! in_category( 'Recipes', $post_id ) ) {
continue;
}
$list .= sprintf(
'<li id="top-list-%1$s">
%5$s
<a title="%3$s" href="%2$s">%4$s</a>
</li>',
absint( $post_id ),
esc_url( get_the_permalink( $post_id ) ),
esc_attr( get_the_title( $post_id ) ),
esc_html( get_the_title( $post_id ) ),
/**
* You can define a different image size here.
* @see https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/
*/
get_the_post_thumbnail( $post_id, 'thumbnail' )
);
}
// Close our ordered list.
$list .= '</ol>';
echo $list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.