How to filter sql only for a specific post type

As @bonger said, let your filters accept a second argument, which will be the instance of WP_Query that’s executing the filter, and check it is indeed the main query for an event:

function single_posts_fields( $sql, $wp_query ) {
    if ( $wp_query->is_main_query() && $wp_query->is_singular( 'event' ) ) {
        // Do your stuff
    }
}

add_filter( 'posts_fields', 'single_posts_fields', 10, 2 /* Number of accepted arguments */ );

function single_posts_join( $sql, $wp_query ) {
    if ( $wp_query->is_main_query() && $wp_query->is_singular( 'event' ) ) {
        // Do your stuff
    }
}

add_filter( 'posts_join', 'single_posts_join', 10, 2 /* Number of accepted arguments */ );

Leave a Comment