【发布时间】:2021-11-14 01:24:05
【问题描述】:
我正在尝试通过带有 ajax 的 post-id 更改模态框内的内容。
我对 ajax 的了解非常有限,并且仍在学习..
所以我设法加载了 ajax 脚本,但是当我打开模式时,我会同时从所有帖子中获取内容,而不是每个帖子都单独获取内容。 我想要实现的是使用 ajax 快速查看帖子, 如何使用带有 ID 的 rel 属性来更改模态框内的 the_content() 内容?
在帖子循环中,我有一个带有动态帖子 ID 的按钮:
<a href="#" rel="<?php the_ID(); ?>" class="btn btn-primary post-link" data-bs-toggle="modal" data-bs-target="#myModal">
QUICK VIEW
</a>
模态:
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div id="the-post-content" class="modal-content">
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">CLOSE</button>
</div>
</div>
</div>
</div>
在function.php中:
add_action( 'wp_ajax_load_post_content', 'load_post_content' );
add_action( 'wp_ajax_nopriv_load_post_content', 'load_post_content' );
function load_post_content() {
$the_post_id = $_POST['the_ID'];
$args = array(
'post_type' => 'post',
'p' => $the_post_id
);
$ajax_query = new WP_Query($args);
$the_content;
if ( $ajax_query->have_posts() ) : while ( $ajax_query->have_posts() ) : $ajax_query->the_post();
$the_content = the_content();
endwhile;
endif;
echo $the_content;
wp_reset_postdata();
die();
}
function enqueue_jquery_ajax(){
?>
<script>
jQuery(document).ready(function(){
jQuery(".post-link").click(function(){
var post_id = jQuery(this).data('id');
var ajaxurl = 'http://my-domain.com/wp-admin/admin-ajax.php';
jQuery.post(
ajaxurl,
{
'url': ajaxurl,
'action': 'load_post_content',
'the_ID': post_id
},
function(response){
jQuery('#the-post-content').html(response);
}
);
return false;
});
});
</script>
<?php
}
add_action('wp_enqueue_scripts','enqueue_jquery_ajax', 99);
顺便说一句。我知道我应该本地化脚本,但现在我只想让它工作..
【问题讨论】:
标签: jquery ajax wordpress wordpress-theming wordpress-rest-api