将无限滚动添加到AJAX加载的类别查询

时间:2014-10-03 作者:mdp8593

Update: This has been resolved. See update below.

在完成了几个不同的在线教程之后,我创建了一个函数,根据从下拉菜单中选择的类别,通过Ajax修改我的帖子显示。

我现在想向Ajax加载的内容添加无限滚动,但我似乎不知道该怎么做。

如果您有任何关于如何进行的想法,我将不胜感激。提前谢谢。

以下是我的php函数:

function ajax_filter_posts_scripts() {
    // Register and enqueue script
    wp_register_script(\'afp_script\', get_stylesheet_directory_uri() . \'/js/ajax-filter-posts.js\', false, null, false);
    wp_enqueue_script(\'afp_script\');

    // localize script
    wp_localize_script( \'afp_script\', \'afp_vars\', array(
        \'afp_nonce\' => wp_create_nonce( \'afp_nonce\' ), 
        \'afp_ajax_url\' => admin_url( \'admin-ajax.php\' ),
    ));
}

add_action(\'wp_enqueue_scripts\', \'ajax_filter_posts_scripts\', 100);

function wp_infinitepaginate() {
    // Verify nonce
    $nonce = $_POST[\'afp_nonce\'];   
    if ( !isset( $nonce ) || !wp_verify_nonce( $nonce, \'afp_nonce\' ) )
        die ( \'Permission denied\');

    if (is_front_page()) { 
        $paged = (get_query_var(\'page\')) ? get_query_var(\'page\') : 1;
    } else {
        $paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
    }
    $cat = $_POST[\'val\'];
    $args = array(
        \'category_name\' => $cat,
        \'post_status\' => \'publish\',
        \'posts_per_page\' => \'4\',
        \'paged\' => $paged,
    );

    query_posts($args);
    get_template_part(\'custom-loop\');

    exit;
}

add_action(\'wp_ajax_infinite_scroll\', \'wp_infinitepaginate\');           // for logged in user
add_action(\'wp_ajax_nopriv_infinite_scroll\', \'wp_infinitepaginate\');    // if user not logged in
以下是我使用的JS:

jQuery(document).ready(function($) {

    jQuery("#la-chooser").change(function() {
        loadArticlebyCat(this.value);
    });

    function loadArticlebyCat(cat){

        data = {
            action: \'infinite_scroll\', 
            val: cat,
            afp_nonce: afp_vars.afp_nonce,
        };

        jQuery.ajax({
            url: afp_vars.afp_ajax_url,
            type:\'post\',
            data: data,
            success: function( data, textStatus, XMLHttpRequest ) {
                jQuery("#tb-ajax-content").html( data );
                console.log( textStatus );
                console.log( XMLHttpRequest );
            },
            error: function( MLHttpRequest, textStatus, errorThrown ) {
                console.log( MLHttpRequest );
                console.log( textStatus );
                console.log( errorThrown );
                jQuery("#tb-ajax-content").html( \'No posts found\' );
            }
        });

        return false;
    }

});
下面是类别下拉筛选器:

Filter by Category: <select id="la-chooser" style="padding:5px 10px;margin-left:5px;">
    <option value="">All Categories</option>
        <?php
            $categories =  get_categories();
            foreach ($categories as $category) {
                $option = \'<option value="\'.$category->category_nicename.\'">\';
                $option .= $category->cat_name;
                $option .= \'</option>\'."\\n";
                echo $option;
            }
        ?>
</select>

1 个回复
SO网友:mdp8593

Update ... Here\'s the Final Code That Worked for Me

这可能并不完美,但对我来说似乎工作得很好,没有任何错误。如果您有任何改进建议,请随时添加。

JS Code

jQuery(document).ready(function($) {

    var count = 2;

    jQuery("#la-chooser").change(function() {
        loadArticlebyCat(this.value);
    });

    function loadArticlebyCat(cat){

        data = {
            action: \'infinite_scroll\', 
            val: cat,
            afp_nonce: afp_vars.afp_nonce,
        };

        jQuery.ajax({
            url: afp_vars.afp_ajax_url,
            type:\'post\',
            data: data,
            success: function( data, textStatus, XMLHttpRequest ) {
                jQuery("#tb-ajax-content").html( data );
                jQuery(\'#infinitBtn span\').html(\'Load More Entries\');
                console.log( textStatus );
                console.log( XMLHttpRequest );
                count = 2;
            },
            error: function( MLHttpRequest, textStatus, errorThrown ) {
                console.log( MLHttpRequest );
                console.log( textStatus );
                console.log( errorThrown );
                jQuery("#tb-ajax-content").html( \'No posts found\' );
            }
        });

        return false;
    }

    jQuery(\'#infinitBtn\').click(function(){
        loadArticle(count);
        count++;
        return false;
    });

    function loadArticle(pageNumber) {

        var cat = jQuery("#la-chooser").val();

        jQuery.ajax({
            url: afp_vars.afp_ajax_url,
            type:\'POST\',
            data: "action=infinite_scroll&page_no="+ pageNumber + "&loop_file=loop&val="+ cat +"&afp_nonce="+afp_vars.afp_nonce,
            success: function(html) {
                if(html=="") {
                    jQuery(\'#infinitBtn span\').html(\'All Entries Loaded\');
                } else {
                    jQuery(\'#infinitBtn span\').html(\'Load More Entries\');
                }
                jQuery("#tb-ajax-content").append(html);
            }
        });

        return false;
    }

});
<小时>

WordPress Functions

请注意,我在子主题中使用了这个,因此如果不使用子主题,您可能希望使用get template directory uri而不是get\\u stylesheet\\u directory\\u uri。

function ajax_filter_posts_scripts() {

    // Register and enqueue script
    wp_register_script(\'afp_script\', get_stylesheet_directory_uri() . \'/js/ajax-filter-posts.js\', false, null, false);
    wp_enqueue_script(\'afp_script\');

    // localize script
    wp_localize_script( \'afp_script\', \'afp_vars\', array(
        \'afp_nonce\' => wp_create_nonce( \'afp_nonce\' ), 
        \'afp_ajax_url\' => admin_url( \'admin-ajax.php\' ),
    ));

}

add_action(\'wp_enqueue_scripts\', \'ajax_filter_posts_scripts\', 100);

function wp_infinitepaginate() {

    // Verify nonce
    $nonce = $_POST[\'afp_nonce\'];   
    if ( !isset( $nonce ) || !wp_verify_nonce( $nonce, \'afp_nonce\' ) )
        die ( \'Permission denied\');

    $paged = $_POST[\'page_no\'];
    $cat = $_POST[\'val\'];
    $args = array(
        \'category_name\' => $cat,
        \'post_status\' => \'publish\',
        \'posts_per_page\' => \'6\',
        \'paged\' => $paged,
    );

    query_posts($args);
    get_template_part(\'custom-loop\');
    wp_reset_query();

    exit;
}

add_action(\'wp_ajax_infinite_scroll\', \'wp_infinitepaginate\');           // for logged in user
add_action(\'wp_ajax_nopriv_infinite_scroll\', \'wp_infinitepaginate\');    // if user not logged in
<小时>

Main Loop Code With Drop-Down Category Selector

<div class="latest-article-chooser clearfix">
    <h1>Latest Blog Posts</h1>
    <p>
        <span>Filter Posts by Category:</span> <select id="la-chooser">
            <option value="">All Categories</option>
                <?php
                    $categories =  get_categories();
                    foreach ($categories as $category) {
                        $option = \'<option value="\'.$category->category_nicename.\'">\';
                        $option .= $category->cat_name;
                        $option .= \' (\'.$category->count.\')\';
                        $option .= \'</option>\'."\\n";
                        echo $option;
                    }
                ?>
        </select>
    </p>
</div>

<div id="tb-ajax-content">

<?php
    if (is_front_page()) { 
        $paged = (get_query_var(\'page\')) ? get_query_var(\'page\') : 1;
    } else {
        $paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
    }
    $count = 1;
    query_posts(array(
        \'post_status\' => \'publish\',
        \'posts_per_page\' => \'6\',
        \'paged\' => $paged,
    ));

    get_template_part(\'custom-loop\');
?>

</div>

<div class="post-clear"></div>

<a class="button sc blue" href="#" id="infinitBtn"><span>Load More Entries</span></a>
<小时>

Custom Loop File (custom-loop.php)

这里包含一些特定于主题的函数,因此您希望用自己的函数(或本机WordPress函数)替换它们。

<?php 
    $count = 1;
    if ( have_posts() ) : while ( have_posts() ) : the_post(); 
?>

    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?> itemscope="itemscope" itemtype="http://schema.org/BlogPosting" itemprop="blogPost">

        <div class="entry-wrap">

            <div class="entry-media">
                <?php 
                    if ( tb_option(\'medium_thumb\') ) { 
                        themebeagle_medium_thumbnail(); 
                    } else {
                        themebeagle_large_thumbnail(); 
                    }
                ?>
            </div>

            <div class="entry-container">

                <header class="entry-header">
                    <?php 
                        themebeagle_entry_title();
                        themebeagle_entry_meta(); 
                    ?>
                </header><!-- .entry-header -->

                <div class="entry-content" itemprop="text">
                    <?php themebeagle_excerpt(); ?>
                </div><!-- .entry-content -->

            </div> <!-- .entry-container -->

            <footer class="entry-footer">
                <?php themebeagle_entry_meta_bottom(); ?>
            </footer><!-- .entry-footer -->

        </div> <!-- .entry-wrap -->

    </article> <!-- article.post -->

<?php 
    $count = $count + 1; 
    endwhile; 
    endif; 
    wp_reset_query();
?>

结束

相关推荐

使用W3TC手动缓存非WP但使用WP的特殊页面(例如AJAX结果

在活动主题文件夹下,我有一个搜索自动完成。php文件,它使用各种WP查询创建智能JSON结果,这些结果通过AJAX传递到jQuery UI自动完成输入字段。它不是一个普通的模板文件(事实上,它不应该真正位于主题文件夹中,它可能是一个插件),但它用以下行加载所需的WP函数:require_once(\"../../../wp-load.php\"); 然而,由于它不执行整个页面执行的正常挂钩,因此它永远不会被W3TC或超级缓存缓存,这显然是次优的,尤其是对于搜索字段上几乎每个按键都会请求的内容。有