phpwordpressclassplugins

Using WP_Query within Plugin


Im currently trying to adjust a Content SlideShow Plugin for Wordpress in order to make it compatible with WPML (Multilingual-Plugin). To achieve this, I simply need to fetch the posts from a specific category, put them into an array and return that array. WP_Query gives me a hard time doing this, as it seems like it's fetching the latest post infinite times in the loop. I'm not experienced in writing Wordpress Plugins, so I would be thankful for any hint you can give me.

This is the code of the plugins class method I'm trying to adjust.

    function get_valid_posts(){

    $validPosts = array();
    $this_post = array();
    $id_pot = array();

    $my_query = new WP_Query('cat=15&showposts=10');

    if($my_query->have_posts()) {
        while ($my_query->have_posts()) : 
            $post = $my_query->post;

            if(!in_array($post->ID, $id_pot)){
                $this_post['id'] = $post->ID;
                $this_post['post_content'] = $post->post_content;
                $this_post['post_title'] = $post->post_title;
                $this_post['guid'] = $post->guid;

                array_push($id_pot, $post->ID);
                array_push($validPosts, $this_post);

            }
        endwhile;
    }

    return $validPosts;
}

Note that I've added the $id_pot array in order to filter duplicate entries, but this shouldn't be necessary if the query / loop would work.

Thanks in advance!


Solution

  • I've managed to solve the problem:

        function get_valid_posts(){
    
        $validPosts = array();
        $this_post = array();
        $id_pot = array();
        $i = 0;
    
        $my_query = new WP_Query('category_name=gallery-post&showposts=10');
    
        if($my_query->have_posts()) {
            while($i < $my_query->post_count) : 
                $post = $my_query->posts;
    
                if(!in_array($post[$i]->ID, $id_pot)){
                    $this_post['id'] = $post[$i]->ID;
                    $this_post['post_content'] = $post[$i]->post_content;
                    $this_post['post_title'] = $post[$i]->post_title;
                    $this_post['guid'] = $post[$i]->guid;
    
                    $id_pot[] = $post[$i]->ID;
                    array_push($validPosts, $this_post);
    
                }
    
                $post = '';
                $i++;
    
            endwhile;
        }
    
        return $validPosts;
    }
    

    $my_query->post returns the data of a specific post. Instead I had to use $my_query->post*s* to get an array with all the posts fetched as an object.