Company Name: ColorMind.space. Business Name: ColorMind.space. Contact Email: info@colormind.space. Number of Services: 10. Services Offered: Image Optimizer, Image Resizer, Image Downloader, Image Converter, Password Generator, FileDrops , Code Diff Checker, ColorLens, Palette Studio, Color Palette Generator.ColorMind.space is an independent browser-based toolkit and is not affiliated with colormind.io.
ColorMind
WordPress

Advancednote 04 of 1603 reasons · 03 notes

WordPressAdvanced

Avoid query_posts in templates

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

Code example

Copy, adapt, and ship.

Read the numbered lines, copy the complete snippet, then adjust the values for your project.

WordPress snippet
$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();
Production-ready starting point11 lines · copy with one click

Why this matters

The production reason.

  1. 01

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

  2. 02

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

  3. 03

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

Platform notes03

How it holds up outside a demo.

  • WordPressUse pre_get_posts for archive-level changes.
  • ThemesUse WP_Query for sidebars and featured sections.
  • PluginsAvoid changing the main query unless your plugin clearly owns the route.