幸亏Sally CJ 我非常接近于通过我正在构建的自动完成搜索来解决所有问题。我遇到的唯一问题是,在用户被带到新页面后(根据他们从下拉/自动完成框中选择的内容),后退按钮不起作用。有时“后退”按钮只是灰显,而有时它会将用户带到看似随机的页面(或之前访问过2-3页的任何页面)。
以下是我的完整代码,如有任何修复建议,将不胜感激。我猜这和window.location.replace(permalink)
但不完全确定。
/**
* Proper way to enqueue scripts.
*/
function theme_enqueue_scripts() {
// Enqueue jQuery UI and autocomplete
wp_enqueue_script( \'jquery-ui-core\' );
wp_enqueue_script( \'jquery-ui-autocomplete\' );
}
add_action( \'wp_enqueue_scripts\', \'theme_enqueue_scripts\' );
/**
* Enqueue ui styles
*/
function theme_enqueue_styles() {
// Enqueue jQuery UI themed styles.
wp_enqueue_style( \'jquery-ui-redmond-core\', \'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/redmond/jquery-ui.min.css\', array(), null );
wp_enqueue_style( \'jquery-ui-redmond-theme\', \'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/redmond/jquery-ui.min.css\', array(), null );
}
add_action( \'wp_enqueue_scripts\', \'theme_enqueue_styles\' );
/**
* Add a shortcode for autocomplete drop down
*
* Use: [autocomplete]
*/
function theme_autocomplete_dropdown_shortcode( $atts ) {
return \'<input type="text" name="autocomplete" id="autocomplete" value="" placeholder="start typing artist name..." />\';
}
add_shortcode( \'autocomplete\', \'theme_autocomplete_dropdown_shortcode\' );
function theme_autocomplete_js() {
$args = array(
\'post_type\' => \'show\',
\'post_status\' => \'publish\',
\'meta_key\' => \'deal_date\',
\'posts_per_page\' => -1 // all posts
);
$posts = get_posts( $args );
if( $posts ) :
foreach( $posts as $k => $post ) {
$source[$k][\'ID\'] = $post->ID;
$source[$k][\'label\'] = $post->post_title ." - ". get_field(\'deal_date\', $post->ID);
$source[$k][\'permalink\'] = get_permalink( $post->ID );
$source[$k][\'value\'] = \'\';
}
?>
<script type="text/javascript">
jQuery(document).ready(function($){
var posts = <?php echo json_encode( array_values( $source ) ); ?>;
jQuery( \'input[name="autocomplete"]\' ).autocomplete({
source: posts,
minLength: 2,
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\' );