Javascript 在 WordPress 中加载更多帖子 Ajax 按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31587210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:51:58  来源:igfitidea点击:

Load More Posts Ajax Button in WordPress

javascriptphpjqueryajaxwordpress

提问by Addzy

I've had a look through the old questions and tried many of the different methods that there seems to be to do this. The closest I've got to working is this one here: How to implement pagination on a custom WP_Query Ajax

我已经浏览了旧问题并尝试了许多似乎可以做到这一点的不同方法。我最接近的工作是这里的这个:How to implement pagination on a custom WP_Query Ajax

I've tried everything and it just doesnt work. Absolutely nothing changes on the page. If you inspect the Load More Button and click it, the jquery is making the Load More Button action as it changes from <a id="more_posts">Load More</a>to <a id="more_posts" disables="disabled">Load More</a>which even that doesnt seem right to me anyway. It's not adding the posts, I think I'm missing something simple but for the life of me I can't work it out.

我已经尝试了一切,但它不起作用。页面上绝对没有任何变化。如果检查负载更多按钮,单击它,在jQuery是使得负载更多按钮动作,因为它从改变<a id="more_posts">Load More</a><a id="more_posts" disables="disabled">Load More</a>其甚至似乎并不正确,我反正。这不是添加帖子,我想我错过了一些简单的东西,但对于我的生活,我无法解决。

The Code in My template file is:

我的模板文件中的代码是:

<div id="ajax-posts" class="row">
    <?php 
    $postsPerPage = 3;
    $args = [
        'post_type' => 'post',
        'posts_per_page' => $postsPerPage,
        'cat' => 1
    ];

    $loop = new WP_Query($args);

    while ($loop->have_posts()) : $loop->the_post(); ?>
        <div class="small-12 large-4 columns">
            <h1><?php the_title(); ?></h1>
            <p><?php the_content(); ?></p>
        </div>
        <?php
    endwhile; 

    echo '<a id="more_posts">Load More</a>';

    wp_reset_postdata(); 
    ?>
</div>

The Code in my functions file is:

我的函数文件中的代码是:

function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];

    header("Content-Type: text/html");
    $args = [
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 1,
        'offset' => $offset,
    ];

    $loop = new WP_Query($args);

    while ($loop->have_posts()) { $loop->the_post(); 
        the_content();
    }
    exit; 
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); 
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

And My JQuery in the footer is:

而我在页脚中的 JQuery 是:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
    jQuery(document).ready( function($) {
        var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";

        // What page we are on.
        var page = 5; 
        // Post per page
        var ppp = 3; 

        $("#more_posts").on("click", function() {
            // When btn is pressed.
            $("#more_posts").attr("disabled",true);

            // Disable the button, temp.
            $.post(ajaxUrl, {
                action: "more_post_ajax",
                offset: (page * ppp) + 1,
                ppp: ppp
            })
            .success(function(posts) {
                page++;
                $("#ajax-posts").append(posts);
                // CHANGE THIS!
                $("#more_posts").attr("disabled", false);
            });
        });
    });
</script>

Can anybody see something I'm missing or able to help?

任何人都可以看到我遗漏的东西或能够提供帮助吗?

回答by dingo_d

UPDATE 24.04.2016.

更新 24.04.2016。

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/about implementing this on Twenty Sixteen theme, so feel free to check it out :)

我已经在我的页面https://madebydenis.com/ajax-load-posts-on-wordpress/上创建了关于在二十十六主题上实现这个的教程,所以请随时查看:)

EDIT

编辑

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

我已经在 25 号上测试过它并且它正在工作,所以它应该适合你。

In index.php(assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

index.php 中(假设您想在主页面上显示帖子,但即使您将其放在页面模板中也应该可以工作)我放置:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

这将输出类别 8 中的 3 个帖子(我在该类别中有帖子,所以我使用了它,你可以使用任何你想要的)。您甚至可以查询您所在的类别

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

这将为您提供在查询中使用的类别 ID。你可以把它放在你的加载器中(加载更多的div),然后用jQuery来拉

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

并拉出类别

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

但现在,你可以忽略这一点。

Next in functions.phpI added

接下来在functions.php中我添加了

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

在现有wp_localize_script. 这将加载 WordPress 自己的 admin-ajax.php,以便我们在 ajax 调用中调用它时可以使用它。

At the end of the functions.php file I added the function that will load your posts:

在functions.php 文件的末尾,我添加了将加载您的帖子的函数:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

在这里,我在数组中添加了分页键,以便循环可以在您加载帖子时跟踪您所在的页面。

If you've added your category in the loader, you'd add:

如果您已在加载程序中添加了类别,则应添加:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POSTarray, and you'll be able to use it in ajax.

而不是 8,你会放$cat. 这将在$_POST数组中,您将能够在 ajax 中使用它。

Last part is the ajax itself. In functions.jsI put inside the $(document).ready();enviroment

最后一部分是ajax本身。在functions.js中我放入了$(document).ready();环境

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

保存它,测试它,它的工作原理:)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

图片作为证据(不要介意粗制滥造的造型,它很快就完成了)。帖子内容也是胡言乱语xD

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

UPDATE

更新

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

对于“无限加载”而不是按钮上的单击事件(只需使其不可见,使用visibility: hidden;),您可以尝试使用

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts()function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

load_posts()当您距离页面底部 100 像素时,这应该会运行该函数。在我网站上的教程的情况下,您可以添加一个检查以查看帖子是否正在加载(以防止触发 ajax 两次),并且您可以在滚动到达页脚顶部时触发它

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100or $('footer').offset().topfor some reason. If that should happen, just increase the number where the scroll goes to.

现在在这些情况下唯一的缺点是您永远无法滚动到$(document).height() - 100$('footer').offset().top由于某种原因的值。如果发生这种情况,只需增加滚动到的数字。

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

您可以通过将console.logs 放入代码中来轻松检查它,并在检查器中查看它们抛出的内容

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

并相应地调整;)

Hope this helps :) If you have any questions just ask.

希望这会有所帮助:) 如果您有任何问题,请提问。

回答by Prashant Kansal

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

如果我没有使用任何类别,那么如何使用此代码?实际上,我想将此代码用于自定义帖子类型。