开发者

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!


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.


You are missing a call to the function the_post();:

while ($my_query->have_posts()) : 
  $my_query->the_post();
  $post = $my_query->post;
  // ...
endwhile;

See The WordPress Loop

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜