Created
January 4, 2019 22:09
-
-
Save cabrerahector/362ea646060da51ca5cc5ca5c16b0886 to your computer and use it in GitHub Desktop.
Most viewed posts from [YEAR] using the WordPress Popular Posts plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Registers shortcode [wpp_top_viewed_posts_from]. | |
* | |
* This function registers a new custom shortcode that | |
* outputs the top viewed posts of a given year. | |
* | |
* Requires PHP 5.3+ to work. | |
* | |
* @author Hector Cabrera (cabrerahector.com) | |
* @param array $atts | |
* @return string | |
*/ | |
function wpp_top_viewed_posts_from( $atts ) { | |
$args = shortcode_atts( array( | |
'year' => date('Y') | |
), $atts ); | |
$key = 'wpp_top_viewed_' . md5(serialize($atts)); | |
$top_posts = get_transient($key); | |
if ( false === $top_posts ) { | |
$join_filter = function($join) use ($args) { | |
global $wpdb; | |
return "INNER JOIN (SELECT SUM(pageviews) AS pageviews, postid FROM `{$wpdb->prefix}popularpostssummary` WHERE view_datetime BETWEEN '{$args['year']}-01-01 00:00:00' AND '{$args['year']}-12-31 23:59:59' GROUP BY postid) v ON p.ID = v.postid"; | |
}; | |
add_filter( 'wpp_query_join', $join_filter ); | |
$top_posts = do_shortcode('[wpp range=custom]'); | |
remove_filter( 'wpp_query_join', $join_filter ); | |
set_transient($key, $top_posts, 1 * DAY_IN_SECONDS); // cache for 1 day | |
} | |
return $top_posts; | |
} | |
add_shortcode( 'wpp_top_viewed_posts_from', 'wpp_top_viewed_posts_from' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment