Skip to content

Instantly share code, notes, and snippets.

@harkor
Last active February 25, 2021 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harkor/fd12d1edcc419b8b99af7ad05ac2f883 to your computer and use it in GitHub Desktop.
Save harkor/fd12d1edcc419b8b99af7ad05ac2f883 to your computer and use it in GitHub Desktop.
<?php
class MyMetaBox {
function __construct(){
add_filter('rwmb_meta_boxes', array(&$this, 'my_meta_box'));
add_action('wp_ajax_get_options', array(&$this, 'get_options'));
}
public function my_meta_box($meta_boxes){
$select_advanced_ajax_id = "_my_select";
$meta_boxes[] = array(
'title' => 'Infos',
'post_types' => array( 'page' ),
'fields' => array(
array(
// Script handle select2
'std' => '
<script type="text/javascript">
jQuery(function($){
var $interface = $("#'. $select_advanced_ajax_id .'_interface");
var $field = jQuery("#'. $select_advanced_ajax_id .'");
$field.on("change", function(){
var $this = $(this);
var value = $this.find(":selected").val();
var text = $this.find(":selected").text();
var data = "";
if(value != ""){ data = JSON.stringify({ value : value, text : text }); }
$interface.val(data);
});
if($interface.val() != ""){
var data = JSON.parse($interface.val());
var newOption = new Option(data.text, data.value, true, true);
$field.append(newOption);
}
});
</script>',
'type' => 'custom_html',
),
array( // Hidden field
'name' => 'My Super Real Select',
'id' => $select_advanced_ajax_id.'_interface',
'type' => 'hidden',
'sanitize_callback' => 'none',
),
array(
// Real field
'name' => 'My Super Select',
'id' => $select_advanced_ajax_id,
'type' => 'select_advanced',
'sanitize_callback' => 'none',
'js_options' => array (
'ajax' => array(
'url' => '/wp-admin/admin-ajax.php',
'dataType' => 'json',
'type' => 'post',
'data' => [
'action' => 'get_options',
],
'delay' => '250',
),
'minimumInputLength' => 0,
'allowClear' => true,
'placeholder' => 'Select an option',
),
),
),
);
return $meta_boxes;
}
public function get_options(){
$results = [
'results' => [],
];
for($i = 1; $i <= 10; $i++):
$results['results'][] = array(
// 'id' => $i,
'id' => $i,
'text' => 'Option '.$i,
);
endfor;
wp_send_json($results);
wp_die();
}
}
new MyMetaBox();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment