我已将帖子 ID 信息存储在 data-*
属性中,我希望通过 &.ajax()
函数在 div 中显示此内容。
这是我正在处理的代码。
显示帖子缩略图的列表项
<li class="homus-partners-section-single" data-post-id="<?php the_ID(); ?>"> <?php the_post_thumbnail(); ?> </li>
我想要显示项目的 div
<div class="homus-partners-detalis"> <div class="homus-partners-detalis-img"> <?php the_post_thumbnail(); ?> </div> <div class="homus-partners-detalis-info"> <h4> <?php the_title(); ?> </h4> <p> <?php the_content(); ?> </p> </div> </div>
ajax 函数
$(document).delegate('li.homus-partners-section-single', 'click', function(event) { event.preventDefault(); var pb_post_id = $(this).data('post-id'); var data = { 'action': 'GetPost', postURL : pb_post_id, }; $.post(ajaxURL, data, function(response) { $( '.homus-partners-detalis' ).html(response); }); });
php 函数
function GetPost(){ $cat = $_POST['catURL']; get_template_part($cat); exit(); } add_action('wp_ajax_nopriv_GetPost', 'GetPost');
编辑2
现在我的代码看起来像这样,但我没有答案
可点击元素的标记
<li class="homus-partners-section-single" data-post-slug="<?php echo $post->post_name;?>"> <?php the_post_thumbnail(); ?>
我想要显示项目的 div
<div class="homus-partners-detalis"> <?php get_template_part('single_pb_post_details'); ?> </div>
我在 div 中调用 php
<div class="homus-partners-detalis-img"> <?php the_post_thumbnail(); ?> </div> <div class="homus-partners-detalis-info"> <h4> <?php the_title(); ?> </h4> <p> <?php homus_excerpt('homus_pb_excerpt'); ?> </p> </div>
ajax函数
$(document).delegate('li.homus-partners-section-single', 'click', function(event) { event.preventDefault(); var pb_post_slug = $(this).data('post-slug'); var data = { 'action': 'GetPostDetails', postURL : "single_pb_post_details.php?slugid="+ pb_post_slug, }; $.post(ajaxURL, data, function(response) { $( '.homus-partners-detalis' ).html(response); alert('Got this from the server: ' + response); }); });
php 函数
function GetPostDetails(){ $details = $_POST['postURL']; get_template_part($details); exit(); } add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
最佳答案
由于get_template_part
只接受不带扩展名的文件名,因此在注释中我们已经达到了以下代码:
$(document).delegate('li.homus-partners-section-single', 'click', function(event) {
event.preventDefault();
var pb_post_slug = $(this).data('post-slug');
var data = {
'action': 'GetPostDetails',
postURL : "single_pb_post_details",
post_id : pb_post_slug
};
$.post(ajaxURL, data, function(response) {
$( '.homus-partners-detalis' ).html(response);
alert('Got this from the server: ' + response);
});
});
响应ajax请求的php代码:
function GetPostDetails(){
get_template_part($_POST['postURL']);
wp_die();
}
add_action('wp_ajax_GetPostDetails', 'GetPostDetails');
add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
在模板文件中,您可以使用以下命令检查 post_id
值:
$_POST['post_id'];
关于javascript - WordPress 通过 ajax 在 div 中加载帖子详细信息和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35696402/