問題描述
我正在使用以下程式碼來檢索帖子:
<?php
$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=5&cat=3');
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>
<h1><a href="<?php%20the_permalink()%20?>"><?php the_title(); ?></a></h1>
<div class="meta">
By <?php the_author() ?>
</div>
<div class="storycontent">
<?php the_excerpt(); ?>
</div>
<?php endwhile; ?>
我需要使用 wp_reset_query()如果我必須使用它應該放在哪裡?
最佳解決方案
你好 @janoChen:
簡單的答案:不。
以下是 WordPRESS v3.0.4 中/wp-includes/query.php 的功能 wp_reset_query()的 PHP 程式碼以及隨後呼叫的函式。您可以看到它主要是在修改全域性變數。
當您使用 new WP_Query($args)時,您將從值中將返回值分配給區域性變數,因此,除非您正在做一些如此複雜的事情,否則您已經知道此問題的答案為否,則不需要呼叫 wp_reset_query():
function wp_reset_query() {
unset($GLOBALS['wp_query']);
$GLOBALS['wp_query'] =& $GLOBALS['wp_the_query'];
wp_reset_postdata();
}
function wp_reset_postdata() {
global $wp_query;
if ( !empty($wp_query->post) ) {
$GLOBALS['post'] = $wp_query->post;
setup_postdata($wp_query->post);
}
}
function setup_postdata($post) {
global $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
$id = (int) $post->ID;
$authordata = get_userdata($post->post_author);
$day = mysql2date('d.m.y', $post->post_date, false);
$currentmonth = mysql2date('m', $post->post_date, false);
$numpages = 1;
$page = get_query_var('page');
if ( !$page )
$page = 1;
if ( is_single() || is_page() || is_feed() )
$more = 1;
$content = $post->post_content;
if ( strpos( $content, '<!--nextpage-->' ) ) {
if ( $page > 1 )
$more = 1;
$multipage = 1;
$content = str_replace("n<!--nextpage-->n", '<!--nextpage-->', $content);
$content = str_replace("n<!--nextpage-->", '<!--nextpage-->', $content);
$content = str_replace("<!--nextpage-->n", '<!--nextpage-->', $content);
$pages = explode('<!--nextpage-->', $content);
$numpages = count($pages);
} else {
$pages = array( $post->post_content );
$multipage = 0;
}
do_action_ref_array('the_post', array(&$post));
return true;
}
-麥克風
次佳解決方案
WP_Query 本身不是必需的,但如果您使用任何相關的功能/方法 (如 the_post()或 setup_postdata()) 填充全域性變數,則必須 (或至少要做的更好) 。
基本上建立新的 WP_Query 物件只是資料檢索,但是使用它來執行主動迴圈並使得模板標籤可訪問的資料可以修改環境,並且以後重新設定好。
總體來說,呼叫它不是有意義的效能損失,所以總是呼叫它更容易,而不是決定是否應該或忘記它,並且有神秘的破壞。
更新
wp_reset_postdata()功能似乎更適合選擇。 wp_reset_query()復位全域性 $wp_query(哪個自定義 WP_Query 物件不影響) 和 $post(它可能如上所述) 變數。 wp_reset_postdata()只能恢復 $post,這應該夠了。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。