优雅的解决方案:Wordpress Ajax。在您的 functions.php 文件中设置一个 ajax 可调用函数,该函数返回数据填充的 html:
一个。向您的 functions.php 文件添加一个 ajax 可调用操作:
add_action("wp_ajax_[function_name]", "function_name");
//If the action wants users to be logged in, you can specify a different function to be called in case a user is not:
//add_action("wp_ajax_nopriv_[function_name]", "[function_name_for_non_logged_users]");
湾。指定要调用的函数(为非登录用户指定第二个,以备不时之需)
function function_name() {
//It is good practice to use nonce verification
if (!wp_verify_nonce( $_REQUEST['nonce'], "function_name_nonce")) {
exit("[Your scary message against bad people]");
}
// Make your query here.
$post_id = $_REQUEST["post_id"];
$post = get_post($id, ARRAY_A);
// Return your data. Here I go with a simple JSON.
$result = json_encode($result);
echo $result;
}
C。在模板中的某处编写前端代码(显然,使其可用于您的 grid.js 调用)。您需要使用您的帖子数据填充 $post。我倾向于使用全局包装器:
<script type="text/javascript">
<?php
$nonce = wp_create_nonce('function_name_nonce');
$endpoint = admin_url('admin-ajax.php');
?>
var Globals = {
nonce: "<?php echo $nonce; ?>",
postId: "<?php echo $post->ID; ?>",
endpoint: "<?php echo $endpoint; ?>"
}
</script>
d。从现在开始,由您来进行 ajax 调用(我没有对您的代码的任何引用),但这非常简单:
$.ajax({
type: "post",
dataType: "json",
url: Globals.endpoint,
data: {
action: "function_name",
post_id: Globals.postId,
nonce: Globals.nonce
},
success: function(response) {
//Aaaaand here's your post data
console.log(response);
}
});
请参阅http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)。
这是一个很好的教程(在 Google 的第一页上找到):http ://wp.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/