Extend WP_Query with custom parameters

function check_custom_query_param( $query ) {
    if ( isset($query->query_vars['custom_param']) && $query->query_vars['custom_param']) {
        $query->custom_param = true;
    }
}
add_action( 'pre_get_posts', 'check_custom_query_param' );


function change_where_query( $where, &$wp_query ) {
    global $wpdb;	
    if ( property_exists ( $wp_query , 'custom_query' ) && $wp_query->custom_query ) {
    	// change the where query
    }
    return $where;
}
add_filter('posts_where', 'change_where_query', 10, 2);

The snippets story

Some weeks ago I wanted to pass a custom parameter to the WP_Query object to change the where-query if the param was true. The problem was, that to extend WP_Query with a parameter, you have to circumvent the filtering of the query options. I solved this by hooking into the pre_get_posts action. There the custom parameter is still available and we can easily add it to the filtered query object.

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *