Hello all. I finally found a little slice of time to try pulling search results from Discourse into Wordpress’s search. The gist is that I created a separate script which uses the Discourse API to do a search query and then I just include this as an iframe in the Wordpress search template.
This may not be the ideal solution for everyone because it show the Discourse results in a separate column from the Wordpress results, not all mixed together.
Here’s a screenshot of how it looks. The forum results are in the grey column next to the Wordpress results:
Step 1:
Create a standalone php script called something like discoursesearch.php and upload it wherever you want to your server:
<?php
define('WP_USE_THEMES', false);
require_once('./wp-blog-header.php');
if (isset($_GET['s'])) {
$search_term = str_replace('+',' ',$_GET['s']);
$search_term = str_replace('\"','"',$_GET['s']);
}else{
exit;
}
// change this to your forum's info
$api_key="YOURAPIKEY";
$api_user="system";
$url_base="https://www.yourforum.com/";
$api_auth="api_key=" . $api_key . "&api_username=" . $api_user;
$ch = curl_init();
$url = $url_base . "search/query.json?term=".urlencode($search_term)."&" . $api_auth;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($ch);
$response_data = json_decode($response, true);
if ( !isset($response_data['errors']) ) {
$all_posts = $response_data['posts'];
$all_topics = $response_data['topics'];
$num_results = count($all_posts);
if ( $num_results > 0 )
echo '<h3>Forum Discussions</h3>';
for ( $i=0; $i<$num_results; $i++ ) {
// see here for all the fields that can be parsed from the search results http://docs.discourse.org/#tag/Search
$topic_title = $all_topics[$i]['title'];
$result_url = $url_base . 't/' . $all_topics[$i]['slug'] . '/' . $all_posts[$i]['topic_id'] . '/' . $all_posts[$i]['post_number'];
$blurb = str_ireplace($search_term,'<b>'.$search_term.'</b>',$all_posts[$i]['blurb']);
$username = $all_posts[$i]['username'];
$avatar = $url_base . str_replace('{size}','30',$all_posts[$i]['avatar_template']);
echo '<p><a target="_new" href="'.$url_base.'u/'.$username.'/summary"><img src="'.$avatar.'" align="left"></a><a target="_new" href="'.$result_url.'">' . $topic_title . '</a>' . '</p><p>' . $blurb . '</p>';
}
echo '<p><a target="_new" href="'.$url_base.'search?q='.$search_term.'">See all forum discussions about: '.$search_term.'</a></p>';
}
?>
Step 2:
Then open up the search template file for your Wordpress theme and put this where ever you’d like the search results to appear:
<iframe src="./discoursesearch.php?s=<?php echo urlencode(get_search_query());?>" height="1000" width="100%" style="height:1000px;width:100%;"></iframe>
That’s it. A bit quick and dirty but it does the job. Hopefully this will be helpful to someone!