web-dev-qa-db-ja.com

投稿を照会するとページがめちゃくちゃになるのはなぜですか。

私は現在テーマに取り組んでいて、ポストテンプレートを設定しました。

この投稿テンプレートは、いくつかのカスタム投稿タイプにリンクされています。

実際の投稿テンプレート自体で自分の投稿タイプをquery_postsすると、何らかの理由でコンテンツが消えます。ここに足りないものはありますか。

ありがとう、マーク

私のループは以下の通りです:

<?php
    $query = 'posts_per_page=10&post_type=articles';
    $queryObject = new WP_Query($query);

    // The Loop...
    if ($queryObject->have_posts()) {
        while ($queryObject->have_posts()) {
            $queryObject->the_post(); the_title(); the_content();
        }
    }
?>
1
Mdunbavan

ループの後に wp_reset_query を使用して、メインループのグローバル投稿データを復元します。

1
Milo

完全を期すために、 wp_reset_query() を使用することは必ずしも間違いではありませんが、新しいインスタンスを使用して2次照会の後に実行する場合、不要な追加操作です。 WP_Query クラスの。 $wp_queryオブジェクトは変更されていないため、リセットする必要はありません。リセットが必要なのは$postグローバルのみです。したがって、この場合、 wp_reset_postdata() で十分です。

参照として / wp-includes/query.php を参照してください。

/**
* Destroy the previous query and set up a new query.
*
* This should be used after {@link query_posts()} and before another {@link
* query_posts()}. This will remove obscure bugs that occur when the previous
* wp_query object is not destroyed properly before another is set up.
*
* @since 2.3.0
* @uses $wp_query
*/
function wp_reset_query() {
    unset($GLOBALS['wp_query']);
    $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
    wp_reset_postdata();
}

/**
* After looping through a separate query, this function restores
* the $post global to the current post in the main query
*
* @since 3.0.0
* @uses $wp_query
*/
function wp_reset_postdata() {
    global $wp_query;
    if ( !empty($wp_query->post) ) {
        $GLOBALS['post'] = $wp_query->post;
        setup_postdata($wp_query->post);
    }
}
0
Johannes Pille