I have been trying to join a custom table with a regular wordpress query, but only under a specific condition (a specific post type).

I have a single-event.php template that runs the main query, and a secondary WP_Query in the sidebar.

Id like to filter the SQL for the main query without interfering with the secondary query.

I am using the following code, unfortunately it affects both queries:

add_filter( 'posts_fields', 'single_posts_fields' );
function single_posts_fields( $sql ) {
    global $wp_query;
    if(is_single() && $wp_query->query_vars['post_type'] == 'event') {

        global $wpdb;

        $sql = $sql . ", 

            some fields...

        ";

    }

    return $sql;
}


add_filter( 'posts_join', 'single_posts_join' );
function single_posts_join( $sql ) {
    global $wp_query;
    if(is_single() && $wp_query->query_vars['post_type'] == 'performance') {
        global $wpdb;

        $table = $wpdb->base_prefix . "events";

        $sql = $sql . "
            LEFT JOIN $table AS something ON something = something 
        ";
    }

    return $sql;
}

The above code succesfully joins a table with a lot of fields to the post object. Unfortunately it also adds this sql to the sidebar query, even though that query is not of the post type “event”. Im resizing that when I get the global $wp_query, im getting the “main” query, and since the main query on single-event.php is of post type “event”, this will effect every query on the page, even if its in its own WP_Query opbject.

How can I get around this and make sure that it ONLY effects the main query on single-event.php?

1 Answer
1

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 Reply

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