提问者:小点点

使用ajax通过WordPress菜单在div中按类别加载最新帖子


我希望我的index.php在顶部有一个类别名称的水平列表,当我单击任何类别名称时,它会在特定的div容器的索引页面上显示最新的10篇文章,无需刷新。这在Wordpress中可能吗?

非常感谢。

<?php $categories = get_categories(); ?>

<ul id="category-menu">
<?php foreach ( $categories as $cat ) { ?>
<li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></li>
<?php } ?>
<div id="main-container">
<div id="loading-animation" style="display: none;"><img src="<?php bloginfo('url'); ?>/images/loading.gif"></div>
<div id="category-listing"></div>
<script>
function cat_ajax_get(catID) {
 jQuery("a.ajax").removeClass("current");
 jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
 jQuery("#loading-animation").show();
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
 jQuery.ajax({
     type: 'POST',
     url: ajaxurl,
     data: {"action": "load-filter", cat: catID },
     success: function(response) {
         jQuery("#category-listing").html(response);
         jQuery("#loading-animation").hide();
         return false;
  }
  });
  }
  </script>
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
$cat_id = $_POST[ '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 ); ?>

<div>
    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>/h1>
</div>

<?php } wp_reset_postdata();

$response = ob_get_contents();
ob_end_clean();

echo $response;
die(1);
}

但是当我点击类别时,它没有显示,但当我选择所有并查看源代码时,结果

有什么帮助吗?


共1个答案

匿名用户

在这种情况下,您不需要弄乱对象缓冲区或 post_attributes() 函数:

function prefix_load_cat_posts () {
    $cat_id = $_POST[ 'cat' ];
    $args = array (
        'cat' => $cat_id,
        'posts_per_page' => 10,
        'order' => 'DESC'

    );
    $posts = get_posts( $args );
    if($posts) {
        foreach ($posts as $post) { ?>
            <div>
                <h1><a href="<?php echo get_the_permalink($post->ID); ?>"><?php echo get_the_title($post->ID); ?></a></h1>
            </div>
        <?php }
    }
    die();
}