Skip to content

Instantly share code, notes, and snippets.

@jdevalk
Last active December 4, 2015 18:09
Show Gist options
  • Save jdevalk/9078ff9dd6cd88313f6d to your computer and use it in GitHub Desktop.
Save jdevalk/9078ff9dd6cd88313f6d to your computer and use it in GitHub Desktop.

If you use HelpScout's Docs product, you want to be able to search that Docs site when you're creating links in your WordPress install. Using the Better Internal Link Search plugin and this piece of code, you can. It'll look like this:

Docs search

Add the code below to one of your must use plugins, or even insert it as a single plugin on its own:

<?php
define( 'HS_API_KEY', '<your Docs API key here>' );
/**
* Class Yoast_HS_Bils_Enhancer
*
* @url https://wordpress.org/plugins/better-internal-link-search/ The plugin we're doing this for
* @url http://developer.helpscout.net/docs-api/articles/search/ The HelpScout Docs Search API
*
* Enhances the Better Internal Link Search search functions with HelpScout Knowledge Base search
*/
class Yoast_HS_Bils_Enhancer {
/**
* Class constructor
*/
public function __construct() {
add_filter( 'better_internal_link_search_modifier_help', array( $this, 'help_modifier' ), 11, 1 );
add_filter( 'better_internal_link_search_modifier-kb', array( $this, 'kb_search' ), 10, 2 );
}
/**
* Make sure the kb command shows up when you type '-' in the link search box
*
* @param $results
*
* @return array
*/
public function help_modifier( $results ) {
$new_modifiers = array(
'kb' => array(
'title' => sprintf( '<strong>-kb {query}</strong></span><span class="item-description">%s</span>', 'Search the HelpScout Knowledge base for a particular topic.' ),
'permalink' => 'https://www.helpscout.net/features/docs/',
'info' => 'Knowledge Base',
),
);
return array_merge( $results, $new_modifiers );
}
/**
* Perform a search through the HelpScout API
*
* @param array $results
* @param array $args
*
* @return array $results
*/
public function kb_search( $results, $args ) {
$request_args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( HS_API_KEY . ':x' )
)
);
$url = add_query_arg( array(
'query' => $args['s'],
'page' => $args['page'],
'visibility' => 'public',
'status' => 'published',
), 'https://docsapi.helpscout.net/v1/search/articles' );
$response = wp_remote_get( $url, $request_args );
if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
$results = array();
$data = json_decode( wp_remote_retrieve_body( $response ) );
foreach ( $data->articles->items as $item ) {
$results[] = array(
'title' => trim( esc_html( strip_tags( $item->name ) ) ),
'permalink' => esc_url( $item->url ),
'info' => esc_html( substr( $item->updatedAt, 0, 10 ) ),
);
}
return $results;
}
return array();
}
}
if ( is_admin() ) {
new Yoast_HS_Bils_Enhancer();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment