Company Name: ColorMind.space. Business Name: ColorMind.space. Contact Email: info@colormind.space. Number of Services: 6. Services Offered: Image Optimizer, Image Resizer, Image Downloader, Image Converter, Password Generator, FileDrops Beta.
ColorMind
Back to WordPress

WordPress / Advanced

Avoid query_posts in templates

Use WP_Query or pre_get_posts so pagination and globals do not break unexpectedly.

Why this matters

The production reason.

query_posts mutates the main query and can break pagination, conditional tags, and global post state.

Use WP_Query for secondary loops or pre_get_posts when you need to adjust the main archive query.

Reset post data after custom loops so template globals return to the expected post.

Copy-ready example
$featured = new WP_Query([
  'posts_per_page' => 3,
  'category_name' => 'featured',
]);

while ( $featured->have_posts() ) {
  $featured->the_post();
  get_template_part( 'template-parts/card' );
}

wp_reset_postdata();

Platform notes.

How this applies outside a perfect demo, including frameworks, CMS platforms, stores, and builder workflows.

WordPress: Use pre_get_posts for archive-level changes.

Themes: Use WP_Query for sidebars and featured sections.

Plugins: Avoid changing the main query unless your plugin clearly owns the route.

Explore other stacks

Jump into a different technology.

Move from this WordPress note into related HTML, CSS, Next.js, JavaScript, React, WordPress, and performance lessons.