【问题标题】:Loading more posts on WP site using AJAX使用 AJAX 在 WP 网站上加载更多帖子
【发布时间】:2015-06-02 20:38:51
【问题描述】:

我在 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;

?>

【问题讨论】:

    标签: javascript php jquery ajax wordpress


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      相关资源
      最近更新 更多