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.
$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();Why this matters
The production reason.
- 01
query_posts mutates the main query and can break pagination, conditional tags, and global post state.
- 02
Use WP_Query for secondary loops or pre_get_posts when you need to adjust the main archive query.
- 03
Reset post data after custom loops so template globals return to the expected post.
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.
Explore other stacks
Jump into a different technology.
16 WordPress notes on this shelf, and six more stacks beside it.
Use next/image for image optimization
Next.js image optimization starts with next/image sizing, lazy loading, modern formats, and predictable dimensions.
Open the noteKeep state close to the interaction
Local state avoids unnecessary parent renders and keeps component intent obvious.
Open the noteAbort stale fetch requests
Cancel outdated browser requests so fast UI changes do not render old data.
Open the noteBuild a CSS gradient generator with code export
A CSS gradient generator should preview color stops, preserve accessible contrast, and export clean CSS code.
Open the noteReduce LCP with image optimization
Reduce LCP with image optimization by resizing, converting, and compressing images before they reach production.
Open the noteUse real buttons for actions
If it changes state, use button. If it navigates, use a link.
Open the note