Foreach生成的定制税务查询,每个查询都有一个AJAX“Load More”按钮

时间:2019-12-26 作者:dmoz

我正在遍历自定义分类术语,为每个术语创建一个WP\\u查询,然后在前端显示帖子。

我也在尝试适应this helpful tutorial(和附带的注释)为每个循环迭代添加一个ajax加载更多按钮。这就是我认为此问题与WP StackExchange上其他帖子的不同之处:在循环查询中添加加载更多按钮,而不是在一个页面上添加单个查询或简单的多个硬编码(非循环)WP\\U查询。

原始教程使用wp_localize_script 将php数据传递给注册的;将jQuery脚本排队,但由于我需要为每个循环创建唯一的变量,所以我似乎无法使用它(教程作者自己也说不要使用wp_localize_script 如果使用自定义WP\\U查询)。那篇帖子上的评论也暗指在多个查询中使用唯一变量,但对于循环查询,我无法理解。

The button that is included in each loop iteration:

// don\'t display the button if there are not enough posts
if (  $unique_query->max_num_pages > 1 )
    echo \'<button class="load-more-btn">Load more</button>\';
我意识到下面的代码还不够简洁(因此我在这里),但我在每个foreach\'d查询中都包含了相同的jQuery,因此我可以为每个循环创建唯一的查询变量(即。current_page_<?php print $cat_string; ?>):

The jQuery included at the end of each loop iteration:

$cat_string = 当前分类术语字符串-ie。los_angeles

<script>
var ajaxurl = "<?php print site_url() . \'/wp-admin/admin-ajax.php\'; ?>",
var posts_<?php print $cat_string; ?> = \'<?php echo serialize( $unique_query->query_vars ) ?>\',
current_page_<?php print $cat_string; ?> = <?php echo $unique_query->query_vars[\'paged\'] ?>,
max_page_<?php print $cat_string; ?> = <?php echo $unique_query->max_num_pages ?>

jQuery(function($){
    $(\'.load-more-btn\').click(function(){
        var button = $(this),
        data = {
            \'action\': \'loadmore\',
            \'query\': posts_<?php print $cat_string; ?>,
            \'page\' : current_page_<?php print $cat_string; ?>
        };

        $.ajax({
            url : ajaxurl, // AJAX handler
            data : data,
            type : \'POST\',
            beforeSend : function ( xhr ) {
                button.text(\'Loading...\');
            },
            success : function( data ){
                if( data ) { 
                    button.text( \'Load more\' ).prev().before(data); // insert new posts
                    current_page_<?php print $cat_string; ?>++;

                    if ( current_page_<?php print $cat_string; ?> == max_page_<?php print $cat_string; ?> ) 
                        button.remove(); // if last page, remove the button
                } else {

                    /* This seems to be where it jumps currently when the button is clicked */

                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });
});
</script>
ajax操作loadmore 被我的函数钩住了。php类似:

function bos_loadmore_ajax_handler(){

    // prepare our arguments for the query
    $args = json_decode( stripslashes( $_POST[\'query\'] ), true );
    $args[\'paged\'] = $_POST[\'page\'] + 1; // we need next page to be loaded
    $args[\'post_status\'] = \'publish\';

    // it is always better to use WP_Query but not here
    query_posts( $args );

    if( have_posts() ) :

        // run the loop
        while( have_posts() ): the_post();

            get_template_part( \'template-parts/event\', \'small\' ); 

        endwhile;

    endif;
    die; // here we exit the script and even no wp_reset_query() required!
}

add_action(\'wp_ajax_loadmore\', \'bos_loadmore_ajax_handler\'); // wp_ajax_{action}
add_action(\'wp_ajax_nopriv_loadmore\', \'bos_loadmore_ajax_handler\'); // wp_ajax_nopriv_{action}
唯一的查询变量正在正确实例化和填充,我可以在Inspector中看到每个税务术语循环的正确输出。

“加载更多”按钮显示正确,因为查询有26个帖子,显示20个帖子,但当我单击按钮时,它变为“加载…”然后消失了。从一些console.log\'s、 对于“找不到数据”,它似乎直接跳转到else分支,因此我认为函数文件中的挂钩操作没有获得正确的查询变量来运行查询。这似乎正确吗?

但是,我不知道查询变量应该如何不同才能得到正确的查询。

更详细地说,每个循环查询的WP\\u Query$args是:

$paged = ( get_query_var(\'page\') ) ? get_query_var(\'page\') : 1;
$args = array(
    \'post_type\'              => array( \'tribe_events\' ),
    \'post_status\'            => array( \'publish\' ),
    \'posts_per_page\'         => 20,
    \'nopaging\'               => false,
    \'paged\'                  => $paged,
    \'tax_query\'              => array(
        array(
            \'taxonomy\'         => \'tribe_events_cat\',
            \'field\'            => \'name\',
            \'terms\'            => $the_cat,
        ),
    ),
);
非常感谢您的帮助。

1 个回复
最合适的回答,由SO网友:dmoz 整理而成

我终于在这篇文章中找到了一些有用的信息:How to "Load More" posts via AJAX?

最终的问题是计算帖子的总页数,并在函数中与挂钩的ajax函数共享该数字。php。

以下是我的页面模板循环:

<div class="events">

    <?php
    $socal_cats = array( \'Los Angeles\', \'San Diego\', \'Las Vegas\' );

    foreach( $socal_cats as $the_cat ) {
        $cat_slug = str_replace(\' \', \'-\', strtolower($the_cat));
        $cat_string = str_replace(\'-\', \'_\', $cat_slug);
    ?>

    <div id="<?php echo $cat_slug; ?>-events">
        <header>
            <h2><?php echo $the_cat; ?></h2>
        </header>
    <div class="events-list">

    <?php
    // WP_Query arguments
    $posts_per_page = 20;
    $paged_main = ( get_query_var(\'page\') ) ? get_query_var(\'page\') : 1;
    $args = array(
        \'post_type\'              => array( \'tribe_events\' ),
        \'post_status\'            => array( \'publish\' ),
        \'posts_per_page\'         => $posts_per_page,
        \'paged\'                  => $paged_main,
        \'tax_query\'              => array(
            array(
                \'taxonomy\'         => \'tribe_events_cat\',
                \'field\'            => \'name\',
                \'terms\'            => $the_cat,
            ),
        ),
    );

    // The Query
    $socalquery = new WP_Query( $args );

    // The Loop
    if ( $socalquery->have_posts() ) {

        $total_posts = $socalquery->found_posts;
        $total_pages = ( ceil( $total_posts / $posts_per_page ) + 1 );
    ?>

    <div class="posts-wrap" id="<?php echo $cat_slug; ?>" data-totalpages="<?php echo $total_pages; ?>">

    <?php
    while ( $socalquery->have_posts() ) {
        $socalquery->the_post();
        get_template_part( \'template-parts/event\', \'small\' );
    }

    // don\'t display the button if there are not enough posts
    if ( $socalquery->found_posts > $posts_per_page )
        echo \'<div class="load-more-wrap"><button class="loadmore"><span class="moretext" data-page="\'.$total_pages.\'">Load more</span></button></div>\';
    ?>
    </div><!-- .posts-wrap -->
    <?php

    } else { 

        get_template_part( \'template-parts/event\', \'none\' );

    }
    ?>

    </div><!-- .events-list -->
</div><!-- .*category*-events -->

<? } // end foreach ?>

<script type="text/javascript">
// Set starting values which to send from Javascript to WP query function...
var ajaxurl = "<?php echo admin_url( \'admin-ajax.php\' ); ?>";

jQuery(function($) {

// When this selector is clicked
$(\'body\').on(\'click\', \'.loadmore\', function() {

    // Get ID of clicked link parent
    var clicked_cat = $(this).parent().parent().attr(\'id\');

    // Get total pagination pages for this section
    var total_pages_for_section = $(\'#\'+clicked_cat+\'.posts-wrap\').data().totalpages;
    // alert(total_pages_for_section);

    // Change link text to provide feedback
    $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap .loadmore .moretext\').text(\'Loading...\');
    $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap .loadmore .moretext\').after(\'<i class="icon fas fa-sync fa-spin"></i>\');
    // $(\'#\'+clicked_cat+\'.load-more-wrap .loadmore i\').attr(\'class\', \'fas fa-cog fa-spin\');

    // Pick up data-page attribute from the clicked link (defaults to 2 at load)
    var clicked_page = $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap .loadmore\').find(\'span\').data().page;

    // 1. Send this package of variables to WP query function
    var data = {
        \'action\': \'loadmore\',
        \'page\': clicked_page, // page of posts to get is the number set in data-page attribute
        \'clicked_cat\': clicked_cat,
        \'security\': \'<?php echo wp_create_nonce("load_more_posts"); ?>\'
    };

    // 2. Send to query function and get results
    $.post(ajaxurl, data, function(response) {

        // Append the returned output to this selector
        $(response).insertBefore(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap\').fadeIn(500);

        // If we have exhausted all post pages, hide the whole "Load More" link
        if (clicked_page >= total_pages_for_section) {
            $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap\').hide();
        // Otherwise, restore it and increment counter
        } else {
            // Change link text back to original
            $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap .loadmore .moretext\').text(\'Load More\');
            $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap .loadmore\').find(\'svg\').remove();
            // Increment "data-page" attribute of clicked link for next click
            $(\'#\'+clicked_cat+\'.posts-wrap .load-more-wrap .loadmore\').find(\'span\').data().page++;
        }
    });

});

});
</script>

</div><!-- .events -->
和功能。php:

// Events Load More button
function bos_loadmore_ajax_handler(){

    check_ajax_referer(\'load_more_posts\', \'security\');

    // 1. Query values are passed from referring page, to Javascript and to this query...
    $paged = $_POST[\'page\'];                  // Passed from page: Which page we are on
    $clicked_cat = $_POST[\'clicked_cat\'];     // ID of the clicked "More" link

    switch ($clicked_cat) {
        case "los-angeles":
            $event_tax_query_term = "los-angeles";
            break;
        case "san-diego":
            $event_tax_query_term = "san-diego";
            break;
        case "las-vegas":
            $event_tax_query_term = "las-vegas";
            break;
        case "bay-area":
            $event_tax_query_term = "bay-area";
            break;
        case "sacramento":
            $event_tax_query_term = "sacramento";
            break;
        case "reno":
            $event_tax_query_term = "reno";
            break;
    }

    // 3. Set query arguments
    $args = array(
        \'post_type\' => array( \'tribe_events\' ),
        \'post_status\' => \'publish\',
        \'posts_per_page\' => 10,
        \'paged\' => $paged,
        \'tax_query\' => array(
            array(
                \'taxonomy\'         => \'tribe_events_cat\',
                \'field\'            => \'slug\',
                \'terms\'            => $event_tax_query_term,
            ),
        ),
    );

    // 4. Query for posts
    $query = new WP_Query( $args );

    // 5. Send results to Javascript
    if ( $query->have_posts() ) :
        ?>
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <?php get_template_part( \'template-parts/event\', \'small\' ); ?>
        <?php endwhile; ?>
        <?php
    endif;

    wp_die();
}
add_action(\'wp_ajax_loadmore\', \'bos_loadmore_ajax_handler\'); // wp_ajax_{action}
add_action(\'wp_ajax_nopriv_loadmore\', \'bos_loadmore_ajax_handler\'); // wp_ajax_nopriv_{action}
希望这能帮助需要ajax的人在同一页面上的多个自定义WP\\U查询上加载更多内容。

相关推荐

WordPress REST终结点无法使用jQuery访问

我在WordPress中有REST端点,我正在尝试使用前面脚本中的jQuery ping它。当通过浏览器询问时,此选项有效:http://example.com/wp-json/wpc_ylp/v2/videos/但当我试图用jQuery从前端访问它时,它不起作用。我尝试了不同的AJAX请求,但没有得到任何响应。有人知道我做错了什么吗?此处为Rest端点:// REST END POINT FOR THE VIDEOS function wpc_ylp_rest_videos( ) { &