cabrerahector / wordpress-popular-posts

WordPress Popular Posts - A highly customizable WordPress widget that displays your most popular posts.
https://wordpress.org/plugins/wordpress-popular-posts/
GNU General Public License v2.0
281 stars 83 forks source link

Add a way to return only a list of post ids or post objects directly #185

Closed codescribblr closed 6 years ago

codescribblr commented 6 years ago

Currently, this plugin is primarily setup to output some type of front-end popular posts snippet. As a developer, this plugin would make an awesome drop-in replacement for a "trending" posts section in many WordPress sites. Most sites already have some method of querying and outputting those posts.

Here's what I'm doing in my functions.php to make the post ids available to my template. It's bad; which is why I'm asking for this feature. :)

function cu_custom_trending_html($wpp_query) {
    $GLOBALS['trending_pids'] = array();
    if(is_array($wpp_query)){
        foreach($wpp_query as $p){
            $pids[] = $p->id;
        }
        $GLOBALS['trending_pids'] = $pids;
        return $pids;
    } else {
        return false;
    }
}
add_filter('wpp_custom_html', 'cu_custom_trending_html');
cabrerahector commented 6 years ago

Hi Jonathan!

You might want to take a look at the WPP_Query class ;)

codescribblr commented 6 years ago

Sweet! I've implemented a new approach using the WPP_Query class. Thanks for pointing that out.

$wpp_query_ids = '';
add_filter( 'wpp_query_fields', 'jrwdev_wpp_return_ids', 10, 2 );
function jrwdev_wpp_return_ids($value, $options) {
    return 'p.ID AS id';
}
if(class_exists('WPP_Query')){
    $wpp_query = new WPP_Query( array('range' => 'weekly', 'post_type' => 'post', 'freshness' => 1, 'order_by' => 'views', 'limit' => 40, 'pid' => implode(',', $trending_args['post__not_in'])) );
    $wpp_query_ids = array_map(function($wppost){return (int)$wppost->id;}, $wpp_query->get_posts());
}
cabrerahector commented 6 years ago

Don't mention it. Glad I could help :)