0
0
Wordpressframework~5 mins

Query parameters in Wordpress

Choose your learning style9 modes available
Introduction

Query parameters let you filter or change what content WordPress shows by adding extra information to the URL.

You want to show posts from a specific category on a page.
You want to display search results based on user input.
You want to list posts by a certain author.
You want to paginate posts to show a limited number per page.
You want to filter posts by custom fields or tags.
Syntax
Wordpress
query_posts( array( 'key' => 'value', 'key2' => 'value2' ) );
Use an associative array to set query parameters.
Common keys include 'category_name', 'author', 'posts_per_page', 'paged', and 's' for search.
Examples
This shows posts only from the 'news' category.
Wordpress
query_posts( array( 'category_name' => 'news' ) );
This shows posts written by the author with ID 3.
Wordpress
query_posts( array( 'author' => 3 ) );
This shows 5 posts per page and displays the second page of results.
Wordpress
query_posts( array( 'posts_per_page' => 5, 'paged' => 2 ) );
This shows posts that match the search term 'apple'.
Wordpress
query_posts( array( 's' => 'apple' ) );
Sample Program

This WordPress template shows the 3 latest posts from the 'news' category. It uses query_posts with query parameters to filter posts. It loops through the posts and displays their titles and excerpts.

Wordpress
<?php
/* Template Name: Custom Query Example */
get_header();

// Show 3 latest posts from category 'news'
query_posts(array('category_name' => 'news', 'posts_per_page' => 3));

if (have_posts()) :
  while (have_posts()) : the_post();
    ?>
    <h2><?php the_title(); ?></h2>
    <p><?php the_excerpt(); ?></p>
    <?php
  endwhile;
else :
  echo '<p>No posts found.</p>';
endif;

wp_reset_query();
get_footer();
?>
OutputSuccess
Important Notes

Always use wp_reset_query() after query_posts() to avoid conflicts.

For better performance and flexibility, consider using WP_Query instead of query_posts.

Query parameters can be combined to create complex filters.

Summary

Query parameters filter WordPress content by adding conditions to the query.

They are passed as an array to query_posts or WP_Query.

Use them to show posts by category, author, search term, or pagination.