Skip to content

Instantly share code, notes, and snippets.

@Coop920
Created June 10, 2019 15:58
Show Gist options
  • Save Coop920/55913c929895316e96912093539c40db to your computer and use it in GitHub Desktop.
Save Coop920/55913c929895316e96912093539c40db to your computer and use it in GitHub Desktop.
/* Adding Rest API To person */
function golf_modify_custom_post_type( $args, $post_type ) {
if ( $post_type == 'golf_person' ) {
$args['show_in_rest'] = true;
$args['rest_base'] = 'custom';
}
return $args;
}
add_filter('register_post_type_args', 'golf_modify_custom_post_type', 10, 2);
function golf_get_player_items() {
/* Old query to grab all of the posts from golf_person post type */
$args = array(
'post_type' => 'golf_person',
'post_status' => 'publish',
'posts_per_page' => -1, // all posts
'meta_query' => array(
array(
'key' => 'person_type',
'value' => 'Player',
'compare' => '=',
),
),
);
$items = array();
if ( $posts = get_posts( $args ) ) {
foreach ( $posts as $post ) {
$items[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'permalink' => get_permalink( $post->ID )
);
}
}
return $items;
}
function golf_register_api_endpoints() {
register_rest_route( 'players/v2', '/posts', array(
'methods' => 'GET',
'callback' => 'golf_get_player_items',
) );
}
add_action( 'rest_api_init', 'golf_register_api_endpoints' );
function theme_autocomplete_dropdown_shortcode( $atts ) {
return '<input type="text" name="autocomplete" id="autocomplete" value="" placeholder="Search by typing player name..." />';
}
add_shortcode( 'autocomplete', 'theme_autocomplete_dropdown_shortcode' );
function theme_autocomplete_js() {
// $args = array(
// 'post_type' => 'golf_person',
// 'post_status' => 'publish',
// 'posts_per_page' => -1, // all posts
// 'meta_query' => array(
// array(
// 'key' => 'person_type',
// 'value' => 'Player',
// 'compare' => '=',
// ),
// ),
// );
// $posts = get_posts( $args );
//var_dump($posts);
// if( $posts ) :
// foreach( $posts as $k => $post ) {
// $source[$k]['ID'] = $post->ID;
// $source[$k]['label'] = $post->post_title; // The name of the post
// $source[$k]['permalink'] = get_permalink( $post->ID );
// }
?>
<script type="text/javascript">
jQuery(document).ready(function($){
//var posts = <?php //echo json_encode( array_values( $source ) ); ?>;
jQuery( 'input[name="autocomplete"]' ).autocomplete({
source: '<?php echo wp_json_encode( esc_url_raw( rest_url( 'players/v2/posts' ) ) ); ?>',,
minLength: 3,
select: function(event, ui) {
var permalink = ui.item.permalink; // Get permalink from the datasource
window.location.replace(permalink);
}
});
});
</script>
<?php
//endif;
}
add_action( 'wp_footer', 'theme_autocomplete_js' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment