Created
February 21, 2021 17:32
-
-
Save raselupm/4217fd4fd1dce8c42cb396715d0d9aa6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Ajax Taxonomy | |
Version: 1.0 | |
*/ | |
wp_enqueue_script('jquery'); | |
add_action('wp_ajax_my_prefix_ajax_taxonomy', 'my_prefix_ajax_taxonomy'); | |
add_action('wp_ajax_nopriv_my_prefix_ajax_taxonomy', 'my_prefix_ajax_taxonomy'); | |
function my_prefix_ajax_taxonomy() { | |
$result = []; | |
$args = array( | |
'taxonomy' => array( 'post_tag' ), // taxonomy name | |
'orderby' => 'id', | |
'order' => 'ASC', | |
'hide_empty' => false, | |
'fields' => 'all', | |
'name__like' => $_GET['q'] | |
); | |
$terms = get_terms( $args ); | |
$count = count($terms); | |
if($count > 0){ | |
foreach ($terms as $term) { | |
$result[] = [ | |
'id' => $term->term_id, | |
'text' => $term->name | |
]; | |
} | |
} | |
echo json_encode($result); | |
die(); | |
} | |
function my_prefix_ajax_select_shortcode() { | |
$html = ' | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" /> | |
<script > | |
jQuery(document).ready(function($) { | |
$(".js-data-example-ajax").select2({ | |
width: 500, | |
theme: "classic", | |
minimumInputLength: 3, | |
placeholder: "Search ...", | |
ajax: { | |
url: "'.admin_url('admin-ajax.php').'", | |
dataType: "json", | |
data: function (params) { | |
return { | |
q: params.term, | |
action: "my_prefix_ajax_taxonomy" | |
}; | |
}, | |
processResults: function (data) { | |
return { | |
results: data | |
}; | |
} | |
} | |
}); | |
}); | |
</script> | |
<form> | |
<select onchange="this.form.submit()" name="tax" class="js-data-example-ajax"></select> | |
</form> | |
'; | |
// display result when user searched | |
if(!empty($_GET['tax'])) { | |
$html .= '<p>You searched for: '.$_GET['tax'].'</p>'; | |
} | |
return $html; | |
} | |
add_shortcode('ajax_select_form', 'my_prefix_ajax_select_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment