Back to Snippets

Dynamic WordPress Post Filtering Using Custom Hooks

PHP WordPress Hooks May 1, 2026

This code snippet provides a custom WordPress hook to filter posts dynamically based on specific conditions such as post meta, categories, or tags. It is useful when you need to modify the post query without altering the core WordPress functionality. The hook utilizes the 'pre_get_posts' action and allows for flexible filtering. Ensure you have a solid understanding of WordPress hooks and query modification before implementing this solution.

Snippet Stats

Lines 30
Characters 1,038
Read 1 min
php • 30 lines
/**
 * Custom WordPress hook to filter posts dynamically.
 *
 * @param WP_Query $query The WordPress query object.
 * @return void
 */
function custom_post_filter( $query ) {
   // Check if the query is the main query and not a preview.
   if ( $query->is_main_query() && !$query->is_preview() ) {
      // Define your custom filter conditions here.
      // For example, filter by a specific post meta.
      $meta_key = 'custom_meta';
      $meta_value = 'custom_value';
      
      // Use the 'meta_query' argument to filter by post meta.
      $query->set( 'meta_query', array(
         array(
            'key' => $meta_key,
            'value' => $meta_value,
            'compare' => '='
         )
      ) );
      
      // Alternatively, you can filter by category or tag.
      // $query->set( 'cat', array( 1, 2, 3 ) ); // Category IDs
      // $query->set( 'tag', array( 'tag1', 'tag2' ) ); // Tag slugs
   }
}
// Hook into the 'pre_get_posts' action to modify the query.
add_action( 'pre_get_posts', 'custom_post_filter' );

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

Related Snippets

View all
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