Skip to content

Instantly share code, notes, and snippets.

@Rahe
Last active December 25, 2015 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rahe/6983193 to your computer and use it in GitHub Desktop.
Save Rahe/6983193 to your computer and use it in GitHub Desktop.
Query posts et WP_Query dans les templates, la bonne façon de faire
<?php get_header ?>
<?php
// Je récupère toutes les pages enfant de la page courante
query_posts(
array(
'post_type' => 'page',
'post_parent' => get_the_ID(),
'nopaging' => true
)
);
if( have_posts() ): ?>
Les pages enfant :
<ul>
<?php while( have_posts() ):
// Ne pas oublier de faire the_post() pour avancer dans la boucle et les articles.
the_post(): ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></li>
<?php endwhile; ?>
</ul>
<?php endif;
// Ici très important, on réinitialise la wp_query globale qui avait été remplacée
wp_reset_query();
get_footer();
?>
<?php get_header ?>
<?php
// Je récupère toutes les pages enfant de la page courante en créant une nouvelle query
$ma_query = new WP_Query(
array(
'post_type' => 'page',
'post_parent' => get_the_ID(),
'nopaging' => true
)
);
if( $ma_query->have_posts() ): ?>
Les pages enfant :
<ul>
<?php while( $ma_query->have_posts() ):
// Ne pas oublier de faire the_post() pour avancer dans la boucle et les articles.
$ma_query->the_post(): ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></li>
<?php endwhile; ?>
</ul>
<?php endif;
// Après la fin de la boucle on réinitialise l'article courant de la query principale.
wp_reset_postdata();
get_footer();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment