使用AJAX在WP站点上加载更多帖子

时间:2015-06-02 20:38:51

标签: javascript php jquery ajax wordpress

我在WP上有网站。我正在尝试使用AJAX加载帖子。与其他此类问题的区别在于我没有分页,帖子部分很简单:附近有两个帖子,下面是按钮。点击此按钮,两个帖子追加前两个帖子。我试图自己编写解决方案,但我在PHP中几乎没有经验,可能就是问题。

发布结构:

<div class="row">       

            <?php if ( have_posts() ) :  while ( have_posts() ) : the_post(); ?>
              <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
              <div class="news-date">
                <?php the_time($format = 'j F Y'); ?>
              </div>
              <div>
                <h3><?php the_title(); ?></h3>
                <p><?php the_content(); ?></p>
              </div>
            </div>
            <?php endwhile; ?>
            <?php endif; ?>

          </div>

          <div class="more-link"><a href="#">Read more></a>
              </div>

JS

    $(function () {

  var posts = 2;
  var posts_offset = 0;

  $("#load-post").click(function (e) {
    e.preventDefault();

    $.ajax({
      type: "POST",
      url: "/wp-content/themes/1cka/load-posts.php",
      dataType: 'html',
      data: {
        posts_offset: posts_offset
      },
      success: function (data) {
        $('.news').append(data);
        posts_offset += 2;

      }
    });
  })
});

PHP

 <?php require_once("header.php"); ?>
<?php
if (isset($_GET['posts_offset']))
{
  $posts_offset = $_GET['posts_offset'];
}

global $post;

// записываем $post во временную переменную $tmp_post
$tmp_post = $post;
$args = array( 'posts_per_page' => 2, 'offset'=> $posts_offset );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
    <?php if ( have_posts() ) :  while ( have_posts() ) : the_post(); ?>
            echo  '<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
              <div class="news-date">
                <?php the_time($format = 'j F Y'); ?>
              </div>
              <div>
                <h3><?php the_title(); ?></h3>
                <p><?php the_content(); ?></p>
              </div>
            </div>'
            <?php endwhile; ?>
            <?php endif; ?>
<?php endforeach; 

$post = $tmp_post;

?>

1 个答案:

答案 0 :(得分:0)

对不起,我没有立即解决方案,但您看过https://github.com/WP-API/WP-API了吗?它为你的大部分wordpress内容实现了一个rest api,你可以通过一个简单的ajax调用来获取任何额外的帖子

相关问题