This code snippet provides a custom WordPress hook to filter posts dynamically based on specific conditions such as post meta, categories, or tags. It...
Back to Snippets
php
• 22 lines
PHP
PHP
PHP
WordPress Custom Hook For Filtering Post Queries By Category
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
/**
* 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 allRegister a custom Gutenberg block pattern with category — reusable hero section pattern with heading, paragraph, and CTA button.
Complete AJAX handler pattern with nonce verification, input sanitization, proper error handling, and script localization.