Recipe: add a search provider to the Addofy search
Goal: results from your own data show up in the Addofy search and palette, in their own group.
The provider
A provider implements AddoBack\Modules\Search\SearchProviderInterface. It has four methods.
use AddoBack\Modules\Search\SearchProviderInterface;
final class Ticket_Search_Provider implements SearchProviderInterface {
public function id(): string {
return 'myplugin_ticket'; // Stable. Also the value of the "types" REST argument.
}
public function label(): string {
return __( 'Tickets', 'myplugin' ); // Group heading.
}
public function available(): bool {
return current_user_can( 'manage_options' ); // Who may search this provider at all.
}
public function search( string $query, int $limit ): array {
$results = array();
foreach ( myplugin_find_tickets( $query, $limit ) as $ticket ) {
$results[] = array(
'type' => 'myplugin_ticket',
'id' => (string) $ticket->id,
'title' => $ticket->subject,
'subtitle' => $ticket->customer,
'url' => admin_url( 'admin.php?page=myplugin&ticket=' . $ticket->id ),
'badge' => $ticket->status,
);
}
return $results;
}
}
Register it
add_filter( 'adba_search_providers', static function ( array $providers ) {
$providers[] = new Ticket_Search_Provider();
return $providers;
} );
Rules to keep
- The provider decides for itself who may search it, in
available(). Addofy does not grant access. $queryis already trimmed and at least two characters.- Never return more than
$limitresults. - Exact matches, such as an order number or a SKU, come first.
- A result has
type,id,title,subtitle,urlandbadge. An optionaltonecolors the badge:neutral,info,success,warningordanger.
Optional: subfilters
Implement FilterableSearchProviderInterface as well to offer subfilters such as a status. It adds filters() (key to label and options) and search_filtered( $query, $limit, $filters ). A provider that only implements the basic interface keeps working; it just has no subfilters.
Related
- Search and palette hooks:
adba_search_providers,adba_search_filtersandadba_search_result. - JavaScript API: the
adba.search.resultsfilter changes results in the browser.