我认为这应该对你有用:
<?php
$posts = get_posts( array(
\'post_type\' => \'postname\',
\'posts_per_page\' => \'1000\'
) );
?>
<select class="form-control" id="selectid" name="selectid" >
<?php foreach( $posts as $post ) : ?>
<option value="<?php esc_attr_e( $post->ID ); ?>"><?php esc_html_e( $post->post_title ); ?></option>
<?php endforeach; ?>
</select>
<!-- Post info -->
<div id="post_info">
</div>
以及javascript部分(您需要将依赖于“jquery”的脚本排队,或者使用另一个支持ajax的库)。
/* script.js, requires jQuery */
;(function($) {
$(document).ready(function() {
var postInfoElement = $("#post_info");
$("#selectid").change(function() {
var postId = $(this).val();
$.ajax({
type: "POST",
data: "action=get_sigle_post&post_id=" + postId,
url: "/wp-admin/admin-ajax.php", // Careful with this, use \'wp_localize_script\' along with the script enqueue method instead.
success: function(response) {
if (!response.success) {
// Something went wrong, response.data should contain an error message
return false;
}
var post = response.data;
// Do whatever you need to do with "post" and "postInfoElement" variables
}
});
});
});
})(jQuery);
最后,您需要一个ajax处理程序
// Define this somewhere within your plugin or theme\'s functions file.
add_action( \'wp_ajax_get_sigle_post\', \'my_func_get_sigle_post\' );
add_action( \'wp_ajax_nopriv_get_sigle_post\', \'my_func_get_sigle_post\' ); // For non-logged in users
function my_func_get_sigle_post() {
$post_id = isset( $_POST[\'post_id\'] ) ? ( int ) $_POST[\'post_id\'] : 0;
if ( ! $post_id ) wp_send_json_error( \'Invalid post id\' );
$post = get_post( $post_id );
if ( ! $post ) wp_send_json_error( \'Could not retrieve the requested post\' );
// Add or remove $post\'s attributes here
// Send the ajax response
wp_send_json_success( $post );
}
不要忘记使用nonce来增强安全性。