Back to Snippets

WordPress Custom Hook For Filtering Post Queries By Category

PHP WordPress Hooks June 22, 2026

This code snippet filters WordPress post queries based on custom conditions, specifically by category, using the 'pre_get_posts' action hook. It is useful when you need to modify the post query without altering the core WordPress code, such as displaying posts from a specific category. The hook checks if the query is the main query and not a preview before applying the filter. To use this snippet, simply attach the function to the 'pre_get_posts' action hook and replace 'my-category' with your desired category slug.

Snippet Stats

Lines 22
Characters 726
Read 1 min
php • 22 lines
/**
 * Filters post queries based on custom conditions.
 *
 * @param WP_Query $query The WordPress query object.
 *
 * @return void
 */
function custom_post_query_filter( $query ) {
   // Check if the query is the main query and not a preview.
   if ( $query->is_main_query() && ! $query->is_preview() ) {
      // Filter posts by a specific category.
      $query->set( 'tax_query', array(
         array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'     => 'my-category', // Replace 'my-category' with your desired category slug.
         ),
      ) );
   }
}
// Attach the function to the 'pre_get_posts' action hook.
add_action( 'pre_get_posts', 'custom_post_query_filter' );

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
PHP
This code snippet provides a custom WordPress hook to filter posts dynamically based on specific conditions such as post meta, categories, or tags. It...

Dynamic WordPress Post Filtering Using Custom Hooks

PHP
Register a custom Gutenberg block pattern with category — reusable hero section pattern with heading, paragraph, and CTA button.

Register Custom Gutenberg Block Pattern

PHP
Complete AJAX handler pattern with nonce verification, input sanitization, proper error handling, and script localization.

Secure AJAX Handler with Nonce Verification