Skip to content

Instantly share code, notes, and snippets.

@zoerooney
Last active August 29, 2015 14:01
Show Gist options
  • Save zoerooney/2195e4055c92c153105d to your computer and use it in GitHub Desktop.
Save zoerooney/2195e4055c92c153105d to your computer and use it in GitHub Desktop.
Display posts by views using Jetpack plugin data, tutorial here: http://zoerooney.com/blog/tutorials/top-posts-by-page-views/ (publish date: 5/16)
<?php if( function_exists( 'stats_get_csv' ) ) :
$top_posts = stats_get_csv( 'postviews', array( 'days' => 21, 'limit' => -1 ) );
$top_ids = array();
foreach ( $top_posts as $top_post ) {
$top_ids[] = $top_post['post_id'];
}
// Check for transient, hat tip Greg Rickaby
if ( false === ( $tops = get_transient( 'popular_posts' ) ) ) :
$top_args = array(
'post_type' => 'post',
'post__in' => $top_ids,
'posts_per_page' => 14
);
$tops = new WP_Query( $top_args );
// Store transient and expire after 24 hours
set_transient( 'popular_posts', $tops, 24 * HOUR_IN_SECONDS );
endif;
if ( $tops->have_posts() ) : ?>
<div id="top-posts-area" class="top-posts-area">
<div class="top-carousel carousel">
<?php while ( $tops->have_posts() ) : $tops->the_post(); ?>
<a class="carousel-item" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('thumbnail'); ?>
<div class="caption">
<h3><?php the_title(); ?></h3>
</div>
</a>
<?php endwhile; ?>
</div>
</div>
<?php endif; wp_reset_postdata();
endif; ?>
$top_posts = stats_get_csv( 'postviews', array( 'days' => 21, 'limit' => -1 ) );
$top_ids = array();
foreach ( $top_posts as $top_post ) {
$top_ids[] = $top_post['post_id'];
}
// Check for transient, hat tip Greg Rickaby
if ( false === ( $tops = get_transient( 'popular_posts' ) ) ) :
$top_args = array(
'post_type' => 'post',
'post__in' => $top_ids,
'posts_per_page' => 14
);
$tops = new WP_Query( $top_args );
// Store transient and expire after 24 hours
set_transient( 'popular_posts', $tops, 24 * HOUR_IN_SECONDS );
endif;
if ( $tops->have_posts() ) : ?>
<div id="top-posts-area" class="top-posts-area">
<div class="top-carousel carousel">
<?php while ( $tops->have_posts() ) : $tops->the_post(); ?>
<a class="carousel-item" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('thumbnail'); ?>
<div class="caption">
<h3><?php the_title(); ?></h3>
</div>
</a>
<?php endwhile; ?>
</div>
</div>
<?php endif; wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment