WordPress的文章类型无限滚动/加载更多按钮 [英] Wordpress Post Type Infinite Scroll / Load more button

查看:215
本文介绍了WordPress的文章类型无限滚动/加载更多按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码当前在WP上显示指定数量(24)的自定义帖子类型,并使用项目类别动态筛选帖子.

I am using the following code to currently display a specified amount (24) of my custom post types on WP, as well as using the project categories to filter through the posts dynamically.

            <!-- Display Filters for Posts --->
            <ul id="filters">
                <li><a href="#" data-filter="*" class="selected">Everything</a></li>
             <?php 
             $terms = get_terms("project_categories"); // get all categories, but you can use any taxonomy
             $count = count($terms); //How many are they?
             if ( $count > 0 ){  //If there are more than 0 terms
             foreach ( $terms as $term ) {  //for each term:
             echo "<li><a href='#' data-filter='.".$term->slug."'>" . $term->name . "</a></li>\n";
             //create a list item with the current term slug for sorting, and name for label
             }
             } 
             ?>
            </ul>

        <!-- Filter Array --->
        <div class="row">
            <div class="col-md-12">

                    <?php $args = array( 'post_type' => 'bw_projects', 'posts_per_page' => 24 ); ?>

                    <?php $the_query = new WP_Query( $args ); ?>

                    <?php if ( $the_query->have_posts() ) : ?>
                        <ul class="img-list" id="isotope-list">
                        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
                     $termsArray = get_the_terms( $post->ID, "project_categories" );  //Get the terms for this particular item
                     $termsString = ""; //initialize the string that will contain the terms
                     foreach ( $termsArray as $term ) { // for each term 
                     $termsString .= $term->slug.' '; //create a string that has all the slugs 
                     }
                     ?> 
                     <li class="<?php echo $termsString; ?>item project home-project"> <?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
                             <a href="<?php echo get_permalink( $post->ID ); ?>">
                                 <?php the_post_thumbnail(); ?>
                                 <span class="text-content"><span><img src="<?php the_field('client_logo'); ?>" alt="" class=""></span></span>
                            </a>
                     </li> <!-- end item -->
                        <?php endwhile;  ?>
                        </ul> <!-- end isotope-list -->
                    <?php endif; ?>

            </div>
        </div><!-- Close Filter Array --->

这是使用同位素过滤从这些指令中进行一些修改后构建的. https://www.aliciaramirez.com/2014/03/integrating -isotope-with-wordpress/

This was built using the Isotope filtering, from these intructions with a few modifications. https://www.aliciaramirez.com/2014/03/integrating-isotope-with-wordpress/

更新:在玛丽莎(Marissa)评论之后,这就是我的代码在过滤器之后的样子.

UPDATE: After Marissa Comments, this is now how my code looks after the filters.

<?php $args = array( 'post_type' => 'bw_projects', 'posts_per_page' => 18 ); ?>

<?php $the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : ?>
<ul class="img-list" id="isotope-list">

<?php $total_posts = wp_count_posts('bw_projects');
$total_posts = $total_posts->publish;
$number_shown = 0; ?>

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
$termsArray = get_the_terms( $post->ID, "project_categories" );  //Get the terms for this particular item
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term 
$termsString .= $term->slug.' '; //create a string that has all the slugs 
}
?> 
<li class="<?php echo $termsString; ?>item project home-project"> <?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
     <a href="<?php echo get_permalink( $post->ID ); ?>">
         <?php the_post_thumbnail(); ?>
         <span class="text-content"><span><img src="<?php the_field('client_logo'); ?>" alt="" class=""></span></span>
    </a>
</li> <!-- end item -->
<?php endwhile;  ?>
</ul> <!-- end isotope-list -->
<?php endif; ?>
            <?php if ( $number_shown < $total_posts ) { ?>
<div class="loadMore" data-offset="<?php echo $number_shown; ?>" data-total="<?php echo $total_posts; ?>">
        Load More
</div>
<?php } ?>

我的loadmore文件处于当前状态:

My loadmore file is in this current state:

<?php
global $post;
$the_offset = trim( sanitize_text_field( wp_unslash( $_POST['pOffset'] ) ) );
$the_total = trim( sanitize_text_field( wp_unslash( $_POST['totalPosts'] ) ) );

$args = array( 'post_type' => 'bw_projects', 'posts_per_page' => 12, 'offset' => $the_offset );
$posts_shown = $the_offset; //Increment this every time you display a project
?>

                <?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
                     $termsArray = get_the_terms( $post->ID, "project_categories" );  //Get the terms for this particular item
                     $termsString = ""; //initialize the string that will contain the terms
                     foreach ( $termsArray as $term ) { // for each term 
                     $termsString .= $term->slug.' '; //create a string that has all the slugs 
                     }
                     ?> 
                     <li class="<?php echo $termsString; ?>item project home-project"> <?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
                             <a href="<?php echo get_permalink( $post->ID ); ?>">
                                 <?php the_post_thumbnail(); ?>
                                 <span class="text-content"><span><img src="<?php the_field('client_logo'); ?>" alt="" class=""></span></span>
                            </a>
                     </li> <!-- end item -->
                        <?php endwhile;  ?>
                        </ul> <!-- end isotope-list -->
                <?php endif; ?>
<?php } ?>

<?php //Then check if we've shown all the posts or not, and we're done.
if ( $posts_shown >= $the_total ) { ?>
    <div id="all-posts-shown"></div>
<?php } ?>

在输出的HTML上,加载更多"按钮显示数据总计"和数据偏移"

On the outputted HTML the load more button is bringing in "data-total" and "data-offset"

<div class="loadMore" data-offset="0" data-total="25">
Load More
</div>

单击加载更多"时,偏移量更改为:

When load more is clicked the offset changes to:

<div class="loadMore" data-offset="12" data-total="25">
Load More
</div>

除了我没有看到额外的帖子正在加载?我想我一定错过了什么.

Except i am seeing no extra posts loading? I think i must have missed something.

推荐答案

在单击或滚动按钮时,可以使用ajax拉动下一轮发布.如果您仍然无法掌握一切,则单击按钮的点击会更容易跟踪.

You can use ajax to pull the next round of posts on button click or scroll. If you're still getting the hang of things, button clicks are a bit easier to track.

在循环显示帖子之前,请先确定您的自定义帖子类型中总共有多少个帖子,以及一个计数器来跟踪您显示了多少个帖子.

Before your loop to display posts, find out how many posts there are in total in your custom post type, and a counter to keep track of how many you've shown.

$total_posts = wp_count_posts('bw_projects');
$total_posts = $total_posts->publish;
$number_shown = 0;

然后在每次显示项目时显示增量编号.然后,在循环之后,检查是否有更多项目要显示,然后添加一个loadmore按钮,其按钮的数据属性存储偏移量(您已经显示了多少个帖子)和总数.

Then increment number shown each time you display a project. Then, after your loop, check if you have more projects to display, then add a loadmore button with data attributes storing the offset (how many posts you've already displayed) and the total.

<?php if ( $number_shown < $total_posts ) { ?>
    <div class="loadMore" data-offset="<?php echo $number_shown; ?>" data-total="<?php echo $total_posts; ?>">
                Load More
    </div>
<?php } ?>

然后,您可以使用AJAX获取下一篇文章.您想先注册您的AJAX函数:

Then you can use AJAX to get the next posts. You want to register your AJAX function first:

<?php
/**
 * Put the following code in your functions.php file
 * get_loadmore is the name of the ajax function we are registering
 * projects-loadmore.php is the file with the contents which will be loaded 
 * when the ajax call is made. 
*/

            add_action('wp_ajax_get_loadmore', 'get_loadmore');
            add_action( 'wp_ajax_nopriv_get_loadmore', 'get_loadmore' );
            function get_loadmore() {

              include(get_template_directory().'/projects-loadmore.php');
              wp_die();

            }
?>

然后您要在单击按钮时设置ajax功能

Then you want to set up your ajax function on button click

<script>
/**---
    Notes:
    When loadMore button is clicked
    This passes information to and pulls content dynamically from the template: projects-loadmore.php
    The returned php and html code is inserted at the end of the #isotope-list div's content
    variables are pulled from the loadmore button's data attributes.
    Variables Passed:
        - postOffset : how many posts have already been displayed
        - totalPosts :  The total number of published posts in this post type.
---**/

$('.loadMore').click(function() {

    //get the offset
    var postOffset = $(this).attr('data-offset');
    var totalPosts = $(this).attr('data-total');
    var thisObj = $(this);

    //get Page Template and put on page
    var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';

    $.ajax({
        type: 'POST',
        url: ajax_url,
        data: {
            action: 'get_loadmore',
            pOffset: postOffset,
            totalPosts: totalPosts,
        },
        dataType: "html",
        success: function(data) {
            $('#isotope-list').append(data);
            $new_offset = parseInt ( thisObj.attr('data-offset') ) + 24;
            thisObj.attr('data-offset', $new_offset) //set the new post offset.
            if ( $('#all-posts-shown')[0] ) {
                thisObj.slideUp(); //hide loadmore if all posts have been displayed.
           }
        },

        error: function(MLHttpRequest, textStatus, errorThrown){
            alert("error");
        }
    });
}); //end of click function 
</script>

那么剩下的就是进入您的projects-loadmore.php文件,获取变量,调整查询并显示帖子:

Then all that's left is to go into your projects-loadmore.php file, grab the variables, tweak your query, and display the posts:

<?php
global $post;
$the_offset = trim( sanitize_text_field( wp_unslash( $_POST['pOffset'] ) ) );
$the_total = trim( sanitize_text_field( wp_unslash( $_POST['totalPosts'] ) ) );

$args = array( 'post_type' => 'bw_projects', 'posts_per_page' => 24, 'offset' => $the_offset );
$posts_shown = $the_offset; //Increment this every time you display a project
?>

//Get your posts and insert your while loop and display code here

<?php //Then check if we've shown all the posts or not, and we're done.
if ( $posts_shown >= $the_total ) { ?>
    <div id="all-posts-shown"></div>
<?php } ?>

在动画和调整方面,您可以做更多的事情,但这足以让您入门.

There's a lot more you can do with this in terms of animations and tweaking, but this should be enough to get you started.

这篇关于WordPress的文章类型无限滚动/加载更多按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆