Pregunta:
Estoy tratando de usar bucles anidados con el complemento de publicaciones a publicaciones. Los dos bucles funcionan, pero el problema surge después del segundo bucle anidado ($ problema). Quiero acceder de nuevo al bucle de publicación $, pero los datos siguen siendo los datos de $ issue.
wp_reset_query()
se restablecerá de nuevo al bucle principal en single.php que no quiero.
Podría usar get_posts()
lugar de new WP_Query, pero quiero poder usar get_template_part()
.
¿Cómo puedo restablecer mis datos al ciclo de publicación, de modo que el segundo 'Título de la publicación' devuelva la publicación, no el número, el título?
Aquí está mi código dentro de 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;
}
Respuesta:
Voy a responder a esto yo mismo, pero fue el muy inteligente @simonwheatley de Code for the People el que resolvió este por mí.
En lugar de usar wp_reset_postdata()
o wp_reset_query()
, puede usar lo siguiente:
$publication->reset_postdata();
Donde $ publicación es su objeto de consulta.
El código de trabajo ahora se ve así:
$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;
}