Support » Plugin: WordPress Popular Posts » get popular post id as an array with no HTML

  • Resolved jspenney

    (@jspenney)


    Hector,
    Is there a query to return the most popular post ids as a text list or an array. I would like to use them in an elementor query, to display popular post in a format to match the other posts on the site
    thanks
    John Penney

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Héctor Cabrera

    (@hcabrera)

    Hi John,

    You can use the WordPressPopularPosts\Query class to fetch an array of popular posts objects. Loop said array to obtain the IDs of each item.

    If you have any further questions don’t hesitate to ask.

    jspenney

    (@jspenney)

    Héctor,
    Thanks for your response. My technical skills are not very deep. Can you give me any insight into how I can install the class in my child them and loop the array?
    I appreciate any help you could provide.
    Thanks,
    John Penney

    Plugin Author Héctor Cabrera

    (@hcabrera)

    Alright, no problem John.

    Untested but it should work. This function will return an array of posts IDs, or an empty array if no popular posts were found:

    
    /**
     * Retrieves popular posts IDs.
     *
     * @param  string $range
     * @param  int    $limit
     * @return array
    function get_popular_posts_ids($range = 'last7days', $limit = 10)
    {
        $post_IDs = array();
    
        $query = new \WordPressPopularPosts\Query([
            'range' => $range,
            'limit' => $limit
        ]);
        $popular_posts = $query->get_posts();
        
        // Popular posts found, get their IDs
        if ( is_array($popular_posts) && ! empty($popular_posts) ) {
            foreach($popular_posts as $popular_post) {
                $post_IDs[] = $popular_post->id;
            }
        }
        
        return $post_IDs;
    }
    

    Usage examples:

    
    // Gets the 10 most viewed posts from the last 7 days
    $post_ids = get_popular_posts_ids();
    
    // Get the 10 most viewed posts from the last 24 hours
    $post_ids = get_popular_posts_ids('last24hours');
    
    // Gets the 3 most viewed posts from the last 30 days
    $post_ids = get_popular_posts_ids('last30days', 3);
    

    Give it a try and let me know how it goes, alright?

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.