如何在自定义wordpress元框中重置查询

时间:2010-12-15 16:52:56

标签: wordpress meta

我正在使用wordpress的这个插件,我被困在一个不会被重置的查询上。 在以下功能中:

function WPSM_artists_autocomplete(){

 $response = array();

 query_posts('post_type=artist&posts_per_page=-1');

  if (have_posts()) : while (have_posts()) : the_post();
   $image_id = get_post_thumbnail_id();  
  $image_url = wp_get_attachment_image_src($image_id,'artist-icon');  
  $image_url = $image_url[0];  

  $response[] = array( get_the_ID() , get_the_title() , null, '<img src="'.$image_url.'" />'. get_the_title()); 
    endwhile; endif;

    wp_reset_query();

    // Write JSON file
 $output = json_encode($response);
 $data = WPSM_CACHE_DIR."/data.json";
 $fh = fopen($data, 'w') or die("can't open file");
 fwrite($fh, $output);
 fclose($fh);

 // Return JSON url
 echo WPSM_CACHE_URL."/data.json";
}

我使用query_posts来填充元数据箱。但是wp_reset_query();似乎没有正常工作。这会影响所有其他元框和帖子相关选项。全局$ post变量设置为此查询的最新值,而不是帖子编辑页面的默认值。

我很想听听如何解决这个插件。可以用一切来让我朝着正确的方向前进。提前谢谢!

干杯,

罗尼

1 个答案:

答案 0 :(得分:6)

我今天遇到了这个并找到了解决办法。

您需要在开始新循环之前存储原始$ post,然后在功能结束时需要将其设置回来。

在您将函数分配给临时变量之前。

$original_query = $wp_query;

然后在你的功能结束时将其设置回来。

   $wp_query = $original_query;
   wp_reset_postdata();

在我使用自定义查询时,不确定上述情况是否适用。

我已在下面发布了我的代码,以便您查看。

            global $wpdb;
            global $post;
            $originalpost = $post;

            $querydetails = "
                SELECT *
                FROM $wpdb->posts
                WHERE $wpdb->posts.post_type = 'projects'
                AND $wpdb->posts.post_status = 'publish'
                ORDER BY $wpdb->posts.post_date DESC
             ";

             $pageposts = $wpdb->get_results($querydetails, OBJECT);

             if ($pageposts) {
                 foreach ($pageposts as $post) { 
                       setup_postdata($post);

                        $postID = get_the_ID();
                        echo '<option value="';
                        echo $postID . '"';
                        foreach ($meta as $m) {
                            if ($postID == $m) echo ' selected="selected" ';
                        }               
                        echo '>';
                        echo the_title();
                        echo '</option>';
                 }
            }

            echo "</select>";
            $this->show_field_end($field, $meta);
            $post = $originalpost;