使用ajax通过post-ID改变wordpress中div中的the_content()内容 &g



我试图改变一个模式内的内容post-id与ajax。

我对ajax的了解非常有限,我还在学习中。

所以我设法加载ajax脚本,但当我打开模态,我得到的内容从所有的帖子一次,而不是每一个帖子对它自己。我想要实现的是一个快速视图的帖子与ajax,如何使用rel属性和ID来改变模态内的_content()内容?

在posts循环中,我有一个动态post-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);

顺便说一下。我知道我应该本地化脚本,但现在我只是想让它工作…

更新:将load_post_content函数替换为以下函数:

function load_post_content() {      
$content_post = get_post($_POST['the_ID']);     
$the_content = $content_post->post_content;     
$the_content = apply_filters('the_content', $the_content);     
$the_content = str_replace(']]>', ']]&gt;', $the_content);      
$title = get_the_title($content_post); // Title     
$thumbnail = get_the_post_thumbnail($content_post); // Thumbnail   
/* if you want display title and thubnails */
$the_content = $title.$thumbnail.$the_content;
print($the_content);      
wp_reset_postdata();     
die(); 
}

相关内容

最新更新