-
Notifications
You must be signed in to change notification settings - Fork 5
Extending Jarvis
Kurtis Shaner edited this page Nov 1, 2018
·
2 revisions
Jarvis can be extended to support custom 'instant suggestions' or 'instants' as they're known in the code. A good example of this feature is the "Recent" suggestion class which prepopulates Jarvis with the most 10 recent items making them instantly suggestible.
Two things are needed to add instant suggestions to Jarvis:
- A class with a
get
method that return an array of modeled suggestions. - A filter letting Jarvis know to include your instant class
<?php
class MyInstantSuggestions {
public function get() {
$models = [];
// add your custom code here to query for and/or hardcode objects
$posts = get_posts();
foreach( $posts as $post ) {
// while it's not required it's recommended to extend one of the prebuilt models from jarvis
// see jarvis/src/php/models
$model = new \Jarvis\Models\Post( $post_id );
// modify your model here
array_push( $models, $model );
}
return $models;
}
}
If you're trying to make a custom action that needs an ajax callback, you should extend the Action
suggestion. It has the same idea but another method and a few properties need defined as well.
class MyCustomAction extends \Jarvis\Suggestions\Action {
// this translates into the rest api route at `/wp-json/jarvis/v1/my_custom_action` that will be the called when your suggestion is invoked
protected $rest_route = 'my_custom_action';
// this array will be passed to the `register_rest_route` function
// @see https://developer.wordpress.org/reference/functions/register_rest_route/ for arguments
protected $rest_args = [];
// which methods should this route allow, also passed to `register_rest_route`
protected $rest_methods = [ 'GET' ];
public function get() {
$model = new \Jarvis\Models\Action();
$action->title = 'My Custom Action';
$action->href = rest_url( self::REST_PREFIX . '/' . $this->rest_route );
$action->type = 'ajax';
$action->icon = 'dashicons-update';
return $action;
}
public function rest_route( $request ) {
// process your route here and return a truthy response for success
return true;
}
}
You can then let jarvis know of your instant class(es) (note the class name as a string)
add_filter( 'jarvis/instants', function( $instants ) {
array_push( $instants, 'MyInstantSuggestions', 'MyCustomAction' );
return $instants;
});