Limiting Search Results to the Active bbPress Forum

Last updated December 18, 2018 « Knowledge Base

Some bbPress forum installs are huge. Perhaps you’d like to help out your visitors by limiting the on-page search to the Forum currently being viewed. If you’d like to do that, you can automagically limit a search form used on any bbPress-powered page generated by get_search_form() (which includes the WordPress Search (not bbPress) Widget):

<?php
function my_get_search_form( $html ) {
// we need to append the current Forum ID so our future hook can use it
if( function_exists( 'bbp_get_forum_id' ) ) {
$forum_id = isset( $_REQUEST['swpforumid'] ) ? absint( $_REQUEST['swpforumid'] ) : bbp_get_forum_id();
if( ! empty( $forum_id ) ) {
$html = str_replace( '</form>', '<input type="hidden" name="swpforumid" value="' . $forum_id . '" /></form>', $html );
}
}
return $html;
}
add_filter( 'get_search_form', 'my_get_search_form' );
function my_searchwp_query_join( $sql, $engine ) {
global $wpdb;
if( isset( $_REQUEST['swpforumid'] ) ) {
$forum_id = absint( $_REQUEST['swpforumid'] );
$meta_query_args = array(
array(
'key' => '_bbp_forum_id',
'value' => $forum_id,
'compare' => '=',
"type" => "NUMERIC",
)
);
$meta_query = new WP_Meta_Query( $meta_query_args );
$mq_sql = $meta_query->get_sql(
'post',
$wpdb->posts,
'ID',
null
);
$sql = $sql . $mq_sql['join'];
}
return $sql;
}
add_filter( 'searchwp_query_main_join', 'my_searchwp_query_join', 10, 2 );
function my_searchwp_query_conditions( $sql, $engine ) {
global $wpdb;
if( isset( $_REQUEST['swpforumid'] ) ) {
$forum_id = absint( $_REQUEST['swpforumid'] );
$meta_query_args = array(
array(
'key' => '_bbp_forum_id',
'value' => $forum_id,
'compare' => '=',
"type" => "NUMERIC",
)
);
$meta_query = new WP_Meta_Query( $meta_query_args );
$mq_sql = $meta_query->get_sql(
'post',
$wpdb->posts,
'ID',
null
);
$sql = $sql . $mq_sql['where'];
}
return $sql;
}
add_filter( 'searchwp_where', 'my_searchwp_query_conditions', 10, 2 );
view raw gistfile1.php hosted with ❤ by GitHub
Fix Search on Your Site. No Coding Required!

Now you can utilize all of the content that's gone unrecognized by native WordPress search instantly with SearchWP

Get SearchWP