WordPress如何通过AJAX按post-ID替换模态框内the_content()内容
核心问题排查与修改方案
你当前返回所有文章内容的核心原因是获取文章ID的逻辑错误,再加上内容返回函数使用不当,修改步骤如下:
1 错误原因说明
- JS 层拿不到正确的文章ID:你将文章ID存在了
rel属性中,但代码里用jQuery(this).data('id')读取,拿到的是空值,传给后端的ID参数无效,查询时没有指定文章就返回了所有内容 - PHP 层内容赋值错误:
the_content()是直接输出内容的函数,不会返回字符串给变量,所以变量赋值是空值 - 内容替换会覆盖关闭按钮:直接替换模态框外层容器的内容,会把底部的关闭按钮也覆盖掉
2 具体修改代码
第一步:修改模态框结构,新增单独的内容容器
避免替换内容时覆盖关闭按钮:
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- 新增专门放文章内容的容器 --> <div id="the-post-content" class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">CLOSE</button> </div> </div> </div> </div>
第二步:修改JS逻辑,正确读取rel属性的文章ID
jQuery(document).ready(function(){ jQuery(".post-link").click(function(){ // 修改为读取rel属性的文章ID var post_id = jQuery(this).attr('rel'); var ajaxurl = 'http://my-domain.com/wp-admin/admin-ajax.php'; jQuery.post( ajaxurl, { 'action': 'load_post_content', 'the_ID': post_id }, function(response){ jQuery('#the-post-content').html(response); } ); return false; }); });
第三步:修改PHP后台接口,正确返回文章内容
function load_post_content() { // 增加ID校验,过滤非法请求 $the_post_id = absint($_POST['the_ID']); if(!$the_post_id) die('无效的文章ID'); $args = array( 'post_type' => 'post', 'p' => $the_post_id, 'post_status' => 'publish' // 仅查询已发布的文章 ); $ajax_query = new WP_Query($args); $the_content = ''; if ( $ajax_query->have_posts() ) : while ( $ajax_query->have_posts() ) : $ajax_query->the_post(); // 用get_the_content获取内容字符串,应用原生过滤器自动处理段落、短代码等格式 $the_content = apply_filters('the_content', get_the_content()); endwhile; endif; echo $the_content; wp_reset_postdata(); die(); }
内容的提问来源于stack exchange,提问作者Meidanm
相关产品推荐
相关产品推荐

