Skip to content

Instantly share code, notes, and snippets.

@dtbaker dtbaker/plugin.php
Created Jul 2, 2013

Embed
What would you like to do?
Hack WordPress to perform an inter-table comparison using 'meta_query'
add_shortcode('bbp-unread-topic-index','dtbaker_bbq_unread_topics');
function dtbaker_bbq_unread_topics(){
if(is_user_logged_in()){
$result = '';
// filter the bbPress query args that are run when [bbp-topic-index] is executed.
add_filter('bbp_after_has_topics_parse_args','unread_bbp_after_has_topics_parse_args',3,1);
// adjust the generated 'where' SQL to perform a table comparison
add_filter('get_meta_sql','dtbaker_get_meta_sql',3,6);
// run the built in bbpress shortcode which does everything nicely
$result .= do_shortcode('[bbp-topic-index]');
// undo our nasty hacks from above.
remove_filter('bbp_after_has_topics_parse_args','unread_bbp_after_has_topics_parse_args',3,1);
remove_filter('get_meta_sql','dtbaker_get_meta_sql',3,6);
// (hopefully) output the list of unread posts to logged in users
return $result;
}else{
return 'Please login to see unread posts';
}
}
// filter the bbPress query args that are run when [bbp-topic-index] is executed.
function unread_bbp_after_has_topics_parse_args($r){
$r['meta_query'] = array(
array(
'key' => bbp_unread_posts_getLastVisitMetaKey(),
'value' => '__DTBAKER_SQL_KEY_TO_REPLACE_IN_META_SQL_FILTER__',
'compare' => '<=',
'type' => 'SIGNED',
),
);
return $r;
}
// (nasty bit) adjust the generated 'where' SQL to perform a table comparison
function dtbaker_get_meta_sql($sql_array, $queries, $type, $primary_table, $primary_id_column, $context){
// print_r(func_get_args());
$meta_table_name = preg_replace('#posts$#','postmeta',$primary_table);
$sql_array['where'] = str_replace(
"CAST(mt1.meta_value AS SIGNED) <= '__DTBAKER_SQL_KEY_TO_REPLACE_IN_META_SQL_FILTER__'",
"CAST(mt1.meta_value AS SIGNED) <= UNIX_TIMESTAMP($meta_table_name.meta_value)",
$sql_array['where']);
return $sql_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.