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

Ste*_*ani 3 meta wordpress

我正在使用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";
}
Run Code Online (Sandbox Code Playgroud)

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

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

干杯,

罗尼

小智 6

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

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

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

$original_query = $wp_query;
Run Code Online (Sandbox Code Playgroud)

然后在函数结束时将其设置回来.

   $wp_query = $original_query;
   wp_reset_postdata();
Run Code Online (Sandbox Code Playgroud)

由于我使用的是自定义查询,因此不确定上述内容是否适用于您的情况.

我在下面发布了我的代码,你可以看一下.

            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;
Run Code Online (Sandbox Code Playgroud)