Hello Nigel,
I hope you are all well.
As you might remember, I'm building a classified ad site with Toolset. Since WP_QUERY could not query the posts table with another table using the JOIN statement to display only ads whose authors have an active membership, I would need to create a custom field for my ad custom post type that would need to be updated whenever there's a change in my member's membership status and then use it in my View's filter.
Well, it turned out that was not easy at all. After working on it for weeks, I still could not get it to work correctly. It has something to do with how my membership plugin sends the event status when someone's membership status changes. It does it asynchronously so I could not tell which event status comes first or second or third... or when it will come...
So I've been looking for an alternative of doing it, and I've found these 2 filter hooks posts_join and posts_where that would allow me to query the posts and postmeta tables with another table in the database at once.
I was able to write the scripts to add the JOIN and WHERE statements to the original query. But the problem is, I don't know how to restrict/assign the new query only to a specific query done by View. As a result, it looks like it applies to every SQL query and crashes my site.
So my question is, what variables or commands can I use to restrict or assign the execution of the scripts below only to a specific query created by the View plugin?
I know with a post, you can restrict it by its ID ($post->ID). Do we have View ID ($view->ID)? Nope.
These are my scripts:
function add_join_clause_to_view_sql( $join, $query ) {
global $wpdb, $post, $wp_query;
$postmeta_table_name = $wpdb->postmeta;
$posts_table_name = $wpdb->posts;
$members_table_name = $wpdb->prefix . 'members';
$join .= "
INNER JOIN
$members_table_name
ON
$posts_table_name.post_author = $members_table_name.user.id
";
return $join;
}
add_filter('posts_join', 'add_join_clause_to_view_sql', 10, 2);
function add_where_clause_to_view_sql( $where, $query ) {
global $wpdb, $post, $membership_ids;
$members_table_name = $wpdb->prefix . 'members';
$where .= "
AND
$members_table_name.memberships IN $membership_ids
";
return $where;
}
add_filter( 'posts_where' , 'add_where_clause_to_view_sql', 10, 2 );
Thank you very much.
chris