使用AJAX和偏移加载Wordpress帖子

时间:2014-02-04 13:03:34

标签: php jquery ajax wordpress

我正在通过AJAX脚本加载wordpress帖子,一切都很好,直到我试图阻止最新的帖子被包含在查询中。当我尝试将offset=1传递给查询时,我会在每次点击“更多帖子”链接时重复相同的帖子。

这是我的自定义页面模板,第一个循环创建一个位于AJAX循环上方的单个英雄帖子:

<?php
/*
Template Name: Home
*/
get_header(); ?>

<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
        <div class="latest-popular">
            <a class="active-link">Most recent</a> <a href="/popular">Most popular</a>
        </div>

        <section class="hero-image">
          <?php $my_query = new WP_Query('orderby=menu_order&posts_per_page=1');
              while ($my_query->have_posts()) : $my_query->the_post();
           ?>
                <figure><?php the_post_thumbnail(); ?>
                    <a href="<?php the_permalink(); ?>" rel="bookmark"><figcaption <?php post_class(); ?>>
                        <h1><?php the_title(); ?></h1>
                        <h2><?php the_field('description'); ?></h2>
                        <p class="credit"><?php the_field('credit'); ?></p>
                        <span class="length"><?php the_field('running_time'); ?> minutes</span>
                    </figcaption></a><?php if( $field = get_field('exclusive') ): ?><section id="exc" <?php post_class(); ?>></section><?php endif; ?><!-- <section class="award"></section>  -->
                </figure>

            <?php endwhile; ?>

        </section>
    </main><!-- #main -->
</div><!-- #primary -->

<!-- Ajax Load More script block -->
    <section id="ajax-load-more">
        <ul class="listing" data-path="<?php echo get_template_directory_uri(); ?>" data-post-type="post" data-display-posts="10" data-post-not-in="<?php echo $postsNotIn; ?>" data-button-text="More Posts" >
        <!-- Load Ajax Posts Here -->
        </ul>
    </section>
    <!-- /Ajax Load More -->

    <!-- Ajax -->
    <script>
    $(function() {  

        if($("#ajax-load-more").length){
            var page = 1,
                $loading = true,
                $finished = false,
                $window = $(window),
                $el = $('#ajax-load-more'),
                $content = $('#ajax-load-more ul'),         
                $path =  $content.attr('data-path');

                if($path === undefined){
                    $path = '/wp-content/themes/my-theme/ajax-load-more.php';
                }
                //Define button text
                if($content.attr('data-button-text') === undefined){
                    $button = 'More posts';
                }else{
                    $button = $content.attr('data-button-text');
                }
                $el.append('<p id="load-more" class="more"><span class="loader"></span><span class="load-more-link">'+$button+'</span></p>');

            //Load posts function
            var load_posts = function(){            


                $('#load-more').addClass('loading');
                $('#load-more span.text').text("Loading...");
                $.ajax({
                    type    : "GET",
                    data    : {                 
                        postType   : $content.attr('data-post-type'),
                        category   : $content.attr('data-category'),
                        author     : $content.attr('data-author'),
                        taxonomy   : $content.attr('data-taxonomy'),
                        tag        : $content.attr('data-tag'),
                        postNotIn  : $content.attr('data-post-not-in'),
                        numPosts   : $content.attr('data-display-posts'),
                        pageNumber : page,
                    },
                    dataType   : "html",
                    url        : $path+"/ajax-load-more.php",
                    beforeSend : function(){
                        if(page != 1){
                            $('#load-more').addClass('loading');
                            $('#load-more span.text').text("Loading...");
                        }
                    },
                    success    : function(data){
                        $data = $('<span>'+data+'</span>');// Convert data to an object   
                        //alert(data);           
                        if(data.length > 1){
                            $data.hide();
                            $content.append($data);  
                            $data.fadeIn(500, function(){
                               $('#load-more').removeClass('loading');
                               $('#load-more span.text').text($button);
                               $loading = false;
                           });
                        } else {
                             $('#load-more').addClass('done');
                             $('#load-more span.text').text($button);
                             $loading = false;
                             $finished = true;
                        }
                    },
                    error     : function(jqXHR, textStatus, errorThrown) {
                        $('#load-more').removeClass('loading');
                        $('#load-more span.text').text($button);
                        //alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
                    }
                });
            }

            $('#load-more').click(function(){
                if(!$loading && !$finished && !$(this).hasClass('done')) {
                    $loading = true;
                    page++;
                    load_posts();
                }       
            });

            load_posts();
        }   

    });
    </script>
<?php get_footer(); ?>

包含AJAX循环的PHP:

<?php
// Our include
define('WP_USE_THEMES', false);
require_once('../../../wp-load.php');

// Our variables
$postType = (isset($_GET['postType'])) ? $_GET['postType'] : 'post';
$category = (isset($_GET['category'])) ? $_GET['category'] : '';
$author_id = (isset($_GET['author'])) ? $_GET['taxonomy'] : '';
$taxonomy = (isset($_GET['taxonomy'])) ? $_GET['taxonomy'] : '';
$tag = (isset($_GET['tag'])) ? $_GET['tag'] : '';
$exclude = (isset($_GET['postNotIn'])) ? $_GET['postNotIn'] : '';
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 6;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;


$args = array(
    'post_type' => $postType,
    'category_name' => $category,

    'author' => $author_id,

    'posts_per_page' => $numPosts,
    'paged'          => $page,

    'orderby'   => 'menu_order',
    'order'     => 'ASC',

    'post_status' => 'publish',
);

// EXCLUDE POSTS
// Create new array of excluded posts
/* Example array from parent page:
   $features = array();
   foreach( $posts as $post):
       setup_postdata($post);
       $features[] = $post->ID;
   endforeach;
   if($features){           
       $postsNotIn = implode(",", $features);
   }
*/


// QUERY BY TAXONOMY
if(empty($taxonomy)){
    $args['tag'] = $tag;
}else{
    $args[$taxonomy] = $tag;
}

query_posts($args); 
?>

<?php 
// our loop  
if (have_posts()) :  
    $i =0;
    while (have_posts()):  
    $i++;
    the_post();?>

<!-- Do stuff -->

<?php endwhile; endif; wp_reset_query(); ?>

正如我上面提到的,添加offset=1导致每次点击“更多帖子”链接时都会调用相同的帖子,我需要将循环中的最新帖子排除在外,任何人都可以了解一下我做错了什么?

2 个答案:

答案 0 :(得分:2)

您必须使用data-post-not-in属性并传递一组帖子ID,因为Offset不适用于分页。

查看github repo @ https://github.com/dcooney/wordpress-ajax-load-more

上的自述文件

一个例子是:

$features = array('7238', '6649', '6951'); // Array of posts to exclude
if($features){
$postsNotIn = implode(",", $features); //Implode the posts and set a variable to pass to our data-post-not-in param.
} 

然后当你像这样调用Ajax时:

<ul class="listing" data-path="<?php echo get_template_directory_uri(); ?>" data-post-type="post" data-display-posts="10" data-post-not-in="<?php echo $postsNotIn; ?>" data-button-text="More posts">

答案 1 :(得分:1)

抵消有打破分页的倾向。在codex上有一篇很好的文章可以解决你的问题。请参阅:http://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination