Redefinindo dados de postagem para o loop anterior em loops aninhados


21

Estou tentando usar loops aninhados com o plugin posts to posts. Os loops funcionam, mas o problema surge após o segundo loop aninhado ($ issue). Desejo acessar o loop de publicação $ novamente, mas os dados ainda são os dados de emissão de $.

wp_reset_query() será redefinido de volta ao loop principal em single.php, o que eu não quero.

Eu poderia usar em get_posts()vez do novo WP_Query, mas quero poder usá-lo get_template_part().

Como posso redefinir meus dados de volta ao loop de publicação, para que o segundo 'Título da publicação' retorne o título da publicação, não o problema?

Aqui está o meu código no single.php:

$publication = new WP_Query( array(
'connected_type'  => 'publication_to_post',
'connected_items' => $post->ID,
'fields'          => 'ids',
'posts_per_page'  => 1,
) );

if ( $publication->have_posts() ) {
while ( $publication->have_posts() ) : $publication->the_post();
    echo '<h2>Publication title = '.get_the_title().'</h2>';
    $pub_id = get_the_ID();

    $issue = new WP_Query( array(
        'connected_type'  => 'publication_to_issue',
        'connected_items' => $pub_id,
        'fields'          => 'ids',
        'posts_per_page'  => 1,
    ) );

    if ( $issue->have_posts() ) {
        while ( $issue->have_posts() ) : $issue->the_post();

            // need to be able to use template parts in here
            echo '<h2>Issue title = '.get_the_title().'</h2>';

        endwhile;
    }

    // This currently returns the issue title, not the publication title
    echo '<h2>Publication title = '.get_the_title().'</h2>';

endwhile;
}

Respostas:


20

Eu mesmo vou responder, mas foi o @simonwheatley muito inteligente do Code for the People que resolveu esse problema para mim.

Em vez de usar wp_reset_postdata()ou wp_reset_query(), você pode usar o seguinte:

$publication->reset_postdata();

Onde $ publicação é seu objeto de consulta.

O código de trabalho agora se parece com:

$publication = new WP_Query( array(
'connected_type'  => 'publication_to_post',
'connected_items' => $post->ID,
'fields'          => 'ids',
'posts_per_page'  => 1,
) );

if ( $publication->have_posts() ) {
while ( $publication->have_posts() ) : $publication->the_post();
    echo '<h2>Publication title = '.get_the_title().'</h2>';
    $pub_id = get_the_ID();

    $issue = new WP_Query( array(
        'connected_type'  => 'publication_to_issue',
        'connected_items' => $pub_id,
        'fields'          => 'ids',
        'posts_per_page'  => 1,
    ) );

    if ( $issue->have_posts() ) {
        while ( $issue->have_posts() ) : $issue->the_post();

            // need to be able to use template parts in here
            echo '<h2>Issue title = '.get_the_title().'</h2>';

        endwhile; $publication->reset_postdata();
    }

    echo '<h2>Publication title = '.get_the_title().'</h2>';

endwhile;
}

11
De fato, esta é a maneira mais inteligente de fazer isso.
David

Isso realmente funciona para você?
GDY

5

Primeiro de tudo, acho que é possível usar get_posts()em combinação com setup_postdata(). Com eles, você pode usar as tags de modelo como em um loop normal do WordPress.

Mas você pode usar esta função também em seus loops aninhados:

# make sure $post is the global in your scope (which should be the case in single.php)
global $post;
if ( $publication->have_posts() ) {
while ( $publication->have_posts() ) : $publication->the_post();
    echo '<h2>Publication title = '.get_the_title().'</h2>';
    $pub_id = get_the_ID();

    # preserve the current post in the higher loop
    $preserve_post = get_post();

    $issue = new WP_Query( array(
        'connected_type'  => 'publication_to_issue',
        'connected_items' => $pub_id,
        'fields'          => 'ids',
        'posts_per_page'  => 1,
    ) );

    if ( $issue->have_posts() ) {
        while ( $issue->have_posts() ) : $issue->the_post();

            // need to be able to use template parts in here
           echo '<h2>Issue title = '.get_the_title().'</h2>';

        endwhile;
    }

    # set the global back to your first loop post
    $post = $preserve_post;
    setup_postdata( $post );
    // This currently returns the issue title, not the publication title
    echo '<h2>Publication title = '.get_the_title().'</h2>';

endwhile;
}
wp_reset_query();
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.