Skip to content

Instantly share code, notes, and snippets.

@jeherve
Last active June 6, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeherve/5f67ad2bc856c594f37eb43192d1932e to your computer and use it in GitHub Desktop.
Save jeherve/5f67ad2bc856c594f37eb43192d1932e to your computer and use it in GitHub Desktop.
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