Skip to content

Instantly share code, notes, and snippets.

@ThierryA
Last active October 8, 2015 07:44
Show Gist options
  • Save ThierryA/47c50a1bcf1bfd51304a to your computer and use it in GitHub Desktop.
Save ThierryA/47c50a1bcf1bfd51304a to your computer and use it in GitHub Desktop.
Beans: add ajax UIkit autocomplete.
<?php
// Do not include the opening php tag if it is already included in your file.
add_action( 'beans_uikit_enqueue_scripts', 'beans_child_enqueue_uikit_assets' );
function beans_child_enqueue_uikit_assets() {
// Add the UIkit autocomplete component.
beans_uikit_enqueue_components( 'autocomplete', 'add-ons' );
}
// Prepend the autocomplete filter to the primary content.
add_action( 'beans_primary_prepend_markup', 'beans_child_autocomplete' );
function beans_child_autocomplete() {
?>
<div class="uk-autocomplete uk-form" data-uk-autocomplete="{source:'<?php echo add_query_arg( array( 'action' => 'beans_child_do_ajax' ), admin_url( 'admin-ajax.php' ) ); ?>'}">
<input type="text">
<script type="text/autocomplete">
<ul class="uk-nav uk-nav-autocomplete uk-autocomplete-results">
{{~items}}
<li data-value="{{$item.value}}">
<a href="{{$item.href}}">
{{$item.title }}
<div>{{$item.text}}</div>
</a>
</li>
{{/items}}
</ul>
</script>
</div>
<?php
}
// Ajax results.
add_action( 'wp_ajax_nopriv_beans_child_do_ajax', 'beans_child_do_ajax' );
add_action( 'wp_ajax_beans_child_do_ajax', 'beans_child_do_ajax' );
function beans_child_do_ajax() {
// $search contains the input text value which can be used to return results accordingly.
$search = beans_post( 'search' );
// Here we are just outputing an array of results, but you could use the $search varariable to define the results.
wp_send_json( array(
array(
'value' => 'result 1',
'title' => 'Result 1',
'href' => '#',
'text' => 'Text for your result 1'
),
array(
'value' => 'result 2',
'title' => 'Result 2',
'href' => '#',
'text' => 'Text for your result 2'
),
array(
'value' => 'result 3',
'title' => 'Result 3',
'href' => '#',
'text' => 'Text for your result 3'
)
) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment