这是我第一次涉足AJAX,我一直在拼接各种教程中的代码,但可能没有帮助。
我的主页(index.php)上有一个类别列表和一个最近帖子的列表。当用户单击某个类别时,我希望更新此帖子列表,而不刷新页面。当前,当我单击一个过滤器时,所有帖子都会加载到我的响应容器中(它不是按类别过滤),并且加载的唯一内容是\\u content(),即使我的模板(listing post.php)要求缩略图、类别等。
我使用骨骼作为启动主题,因此wp\\u localize\\u脚本位于该文件中(它正在工作)。我只包含了我知道有问题的代码(我知道站点的其余部分和JS工作正常)。
bones.php
//Add AJAX path to use in load-posts.js
$getPath = array(\'ajaxURL\' => admin_url(\'admin-ajax.php\'));
wp_localize_script(\'main-js\', \'pathToFile\', $getPath);
functions.php
//AJAX Category Filter
add_action( \'wp_ajax_load_cat_posts\', \'load_cat_posts\' );
add_action( \'wp_ajax_nopriv_load_cat_posts\', \'load_cat_posts\' );
function load_cat_posts () {
$cat_id = get_post_meta($_REQUEST[\'cat\']);
$args = array (
\'cat\' => $cat_id,
\'posts_per_page\' => 10,
\'order\' => \'DESC\'
);
$posts = get_posts($args);
ob_start ();
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<?php get_template_part( \'partials/listing\', \'post\'); ?>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
index.php
<?php $categories = get_categories(); ?>
<ul class="category-filters">
<?php foreach ( $categories as $cat ) { ?>
<li id="cat-<?php echo $cat->term_id; ?>">
<a class="<?php echo $cat->slug; ?> ajax" data-cat="<?php echo $cat->term_id; ?>" href="javascript:void(0)"><?php echo $cat->name; ?></a>
</li>
<?php } ?>
</ul>
listing-post.php
<li class="standard-post">
<article id="<?php echo sanitize_title_with_dashes( get_the_title() ); ?>" <?php post_class(); ?> role="article">
<?php if (has_post_thumbnail()) { ?>
<div class="article-image">
<?php the_post_thumbnail(large); ?>
</div>
<?php } ?>
<div class="article-left">
<?php foreach((get_the_category()) as $category) { ?>
<span class="article-category"><?php echo $category->cat_name . \' \';?></span>
<?php } ?>
</div>
<div class="article-right">
<header class="article-header">
<h1 class="article-title"><?php the_title(); ?></h1>
<p class="article-time">
<?php printf( __( \'<time class="updated" datetime="%1$s" pubdate>%2$s</time>\', \'bonestheme\' ), get_the_time(), get_the_time(get_option(\'date_format\'))); ?>
</p>
</header>
<section class="entry-content">
<?php the_content(); ?>
</section>
</div>
</article>
</li>
load-posts.js
function cat_ajax_get(currentCat) {
$(\'a.ajax\').removeClass(\'current\');
$(\'a.ajax\').addClass(\'current\');
$(\'#loading-animation\').show();
$.ajax({
type: \'POST\',
url: ajaxurl,
data: {action: \'load_cat_posts\', cat: currentCat },
success: function(response) {
$(\'.article-listing\').html(response);
$(\'#loading-animation\').hide();
return false;
}
});
};
ajaxFilters: function() {
$(\'.category-filters a\').on(\'click\', $.proxy(function(clickEvent) {
$clickTarget = $(clickEvent.currentTarget);
var currentCat = $clickTarget.attr(\'data-cat\');
cat_ajax_get(currentCat);
},this));
}