【问题标题】:Get the posts count in JS (Wordpress)获取 JS 中的帖子数(Wordpress)
【发布时间】:2015-08-17 08:12:39
【问题描述】:

我在 WP 上有网站。

我正在使用 AJAX 来显示我的帖子。单击“更多”按钮会出现另外两个帖子。当显示所有帖子时,我试图隐藏按钮。但是出了点问题。

我不明白如何将帖子数计入 JS(这是另一种变体),因为构造 var posts_count = "<?php echo $posts_count; ?> 不起作用 - 它只提供字符串!

JS

$(function () {

  var posts = 2; //posts shown
  var posts_offset = 2;



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


    $.ajax({
      type: "GET",
      url: "/wp-admin/admin-ajax.php",
      data: ({
        action: 'loadMore',
        posts_offset: posts_offset
      }),
      success: function (data) {
        $('.news #content').append(data);
        posts_offset += 2;

      }
    });


  });


});

PHP

function loadMore() {



    $posts_count = wp_count_posts()->publish; 

    $posts_offset = $_GET['posts_offset'];


    // get your $_GET variables sorted out

    // setup your query to get what you want
    query_posts( array( 'posts_per_page' => 2, 'offset'=> $posts_offset ) );

    // initialsise your output
    $output = '';

    // the Loop
    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;

  if ($posts_count - ($posts_offset + 2) <= 0) { ?>
      <script>$("#load-more").hide();</script>
    <?php }


    // Reset Query
    wp_reset_query();

    die($output);

}

此代码有效,但在隐藏按钮部分无效

【问题讨论】:

  • 你没有回显脚本部分

标签: javascript php jquery ajax wordpress


【解决方案1】:

如下更改您的代码:

PHP

<script>function hideLoadMore(){$("#load-more").hide();}</script>

JS

success: function (data) {
    $('.news #content').append(data);
    posts_offset += 2;
    if(hideLoadMore) { 
        hideLoadMore(); 
    }
  }

【讨论】:

  • 你的按钮id是“load-more”还是“load-post”,你想隐藏哪一个?
  • 因为点击事件发生在“load-post”而不是“load-more”
【解决方案2】:

你不是 echo 脚本部分。

if ($posts_count - ($posts_offset + 2) <= 0) {
      echo '<script>$("#load-more").hide();</script>';
}

为什么不将 javascript 部分与 php 分开?如果您从 ajax 处理脚本逻辑会更优雅。在 php 中,如果条件不满足,您将发回一些响应,然后您从 javascript 处理 DOM 操作。

【讨论】:

  • 它对我不起作用(更优雅的解决方案呢 - 我对 PHP 有一点经验,所以我不知道如何制作它
猜你喜欢
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 2010-12-04
  • 1970-01-01
  • 2015-12-27
  • 2018-04-05
相关资源
最近更新 更多