【发布时间】:2023-03-16 19:30:02
【问题描述】:
我最近开始使用 WordPress,并做了一个关于 Ajax 的小教程。
目前,我正在尝试检索帖子的内容,然后将它们显示在另一个 div 的同一页面上(已使用短代码创建)。一切正常,除了响应显示在整个页面上并且未显示在所选 div 中 - 从而清除其他内容。
请在下面找到我写的代码的sn-ps:
////CREATING SHORT CODES
public function posts_callback($atts = null, $content = null) {
$args = array("post_type" => "post", "orderby" => "date", "order" => "DESC", "post_status" => "publish");
$posts = new WP_Query($args);
?>
<div style ="text-align: center" >
<?php
if ($posts->have_posts()):
while ($posts->have_posts()):
$posts->the_post();
$link = admin_url('admin-ajax.php?action=post_content&post_id='.get_the_ID());
?>
<div id="posts_callback_div" style="display: inline-block; width: 300px; border-color: #333; border-style: solid; border-width: 2px; margin-top: 15px;">
<a class='short_code_link' data-post-id='<?php echo get_the_ID() ?>' href='<?php echo $link ?>' >
<?php echo get_the_title(); ?>
</a>
</div>
<?php
endwhile;
else:
echo "";
die();
endif;
?>
</div>
<?php
}
public function custom_container_shortCode() {
?>
<div class="custom_container" id="custom_container" style="width: 300px; border-color: #333; border-style: solid; border-width: 2px; margin-top: 15px;">
Hi, if you can still see me then the ajax is not working!
</div>
<?php
}
//JQUERY部分
(function ($) {
'use strict';
$(".short_code_link").click(function (e) {
e.preventDefault();
postID = jQuery(this).attr("data-post-id");
jQuery.ajax({
type: "GET",
url: myAjax.ajaxurl,
// dataType: "html",
cache: false,
data: {
action: "post_content",
post_id: postID,
},
success: function (response) {
jQuery("#custom_container").html(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
});
})(jQuery);
//PHP 处理程序
//CREATING AJAX API TO RETRIEVE POST CONTENT
public function post_content() {
$post_id = $_GET["post_id"];
$content_post = get_post($post_id);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]$gt', $content);
echo $content;
die();
}
你能指出我做错了什么吗?
【问题讨论】: