带加载更多按钮的AJAX过滤器

时间:2021-01-31 作者:user3653409

我正在努力使用混合了加载更多按钮的ajax过滤器。我会尽量说清楚的

我有一个自定义的帖子类型叫做Companies. 我已经创建了一个页面,列出了所有这些分类,它们可以通过分类术语进行过滤(例如:证书、区域等…)。选择一些过滤器,然后单击apply 并使用Ajax显示相应的结果。

此外,只显示前12个结果,还有一个loadmore按钮,它也可以使用Ajax加载更多结果

companies.php

<?php

/*****
Here\'s my init query listing all of them
*****/

$all_companies = new WP_Query(array(\'post_type\' => \'companies\', \'posts_per_page\' => 12, \'paged\' => $paged, \'order\' => \'ASC\', \'orderby\' => \'ID\'));

<?php if($all_companies->have_posts()): ?>
<div class="companies_results">
    <?php while ( $all_companies->have_posts() ) : $all_companies->the_post(); ?>
        <?php get_template_part( \'template-parts/bloc_companies\' ); ?>
    <?php endwhile; ?>
</div>
<?php endif; wp_reset_query(); ?>

<div class="loadmore">
    <div>
        <span>Show more</span>
    </div>
</div>

functions.php

<?php

/**
 * AJAX
 *
 * @return void
 */

/***** 
Here\'s my loadmore script 
*/
function misha_my_load_more_scripts() {
 
    wp_enqueue_script(\'jquery\');
 
    global $all_companies;

    wp_localize_script( \'cs-ajax\', \'misha_loadmore_params\', array(
        \'ajaxurl\' => site_url() . \'/wp-admin/admin-ajax.php\', // WordPress AJAX
        \'posts\' => json_encode( $all_companies->query_vars ), // everything about your loop is here
        \'current_page\' => get_query_var( \'paged\' ) ? get_query_var(\'paged\') : 1,
        \'max_page\' => $all_companies->max_num_pages
    ) );
 
    wp_enqueue_script( \'cs-ajax\' );

    wp_reset_postdata();
}
 
add_action( \'wp_enqueue_scripts\', \'misha_my_load_more_scripts\' );


/***** 
Displaying loadmore script results
*/
function misha_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() ) :
 ?>
     <?php
 // run the loop
     while( have_posts() ): the_post(); ?>
         <?php get_template_part( \'template-parts/bloc_companies\' ); ?>
     <?php

     endwhile
     ?>
 

     <?php

 endif;
 die;
}

add_action(\'wp_ajax_loadmore\', \'misha_loadmore_ajax_handler\');
add_action(\'wp_ajax_nopriv_loadmore\', \'misha_loadmore_ajax_handler\');



/***** 
Displaying filtered companies results
*/

add_action( \'wp_ajax_companies\', \'display_companies\' );
add_action( \'wp_ajax_nopriv_companies\', \'display_companies\' );

function display_companies() {
  
    $certifs = $_POST[\'certifs\'];
    $areas = $_POST[\'aread\'];
    
    if($areas == \'\') {
        $args_areas_query = array(\'\');
    } else {
        $args_areas_query = array(
            \'taxonomy\' => \'company_areas\',
            \'field\'    => \'slug\',
            \'terms\'    => $areas,
        );
    }

    if($certifs == \'\') {
        $args_certifs_query = array(\'\');
    } else {
        $args_certifs_query = array(
            \'taxonomy\' => \'company_certifications\',
            \'field\'    => \'slug\',
            \'terms\'    => $certifs,
        );
    }

    
    //Args form main loop
    $args = array(
        \'post_type\' => \'companies\',
        \'post_status\' => \'publish\',
        \'posts_per_page\' => 12,
        \'tax_query\' => array(
            $args_areas_query,
            $args_certifs_query
        )
    );

    $ajax_query = new WP_Query($args);
    $num = $ajax_query->post_count;

    if($ajax_query->have_posts()) {
        ?>
        <div class="companies_results">
        <?php
        while ( $ajax_query->have_posts() ) : $ajax_query->the_post(); ?>
            <?php get_template_part( \'template-parts/bloc_companies\' ); ?>
        <?php endwhile;
        } else {
            echo \'<p>Not found</p>\';
        }    
        ?>
        </div>
        <?php

        wp_reset_query();


    wp_die();
}

Ajax.js

//Loadmore ajax on click
$(\'.loadmore\').click(function() {
    
    var button = $(this),
        data = {
        \'action\': \'loadmore\',
        \'query\': misha_loadmore_params.posts, // that\'s how we get params from wp_localize_script() function
        \'page\' : misha_loadmore_params.current_page
    };

    $.ajax({
        url : misha_loadmore_params.ajaxurl, // AJAX handler
        data : data,
        type : \'POST\',
        beforeSend : function ( xhr ) {
            button.text(\'Loading...\'); // change the button text, you can also add a preloader image
        },
        success : function( data ){
            if( data ) { 
                $(\'.companies_results\').imagesLoaded( function() {
                    $(\'.companies_results\').append(data);
                });
                
                misha_loadmore_params.current_page++;

                if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page ) 
                    button.remove(); // if last page, remove the button

                // you can also fire the "post-load" event here if you use a plugin that requires it
                // $( document.body ).trigger( \'post-load\' );
            } else {
                button.remove(); // if no data, remove the button as well
                console.log(\'error\');
            }
        }
    });
});

//Apply filters ajax query
$(\'.applyfilter\').click( function() {

    var certifs = [];
    var areas = [];

    //Get  values
    $(\'.block-filter_areas input:checked\').each(function() {
        areas.push($(this).val());
    });
    $(\'.block-filter_certifs input:checked\').each(function() {
        certifs.push($(this).val());
    });
    


    $.ajax({
        url: misha_loadmore_params.ajaxurl,
        type: "POST",
        data: {
        \'action\': \'companies\',
        \'areas\': areas,
        \'certifs\': certifs,
        }
    }).done(function(response) {
        // when filter applied:
        // set the current page to 1
        misha_loadmore_params.current_page = 1;

        // set the new query parameters
        misha_loadmore_params.posts = response.posts;

        // set the new max page parameter
        misha_loadmore_params.max_page = response.max_page;

        $(\'.companies_results\').html(response);

        // hide load more button, if there are not enough posts for the second page
        if ( response.max_page < 2 ) {
            $(\'.loadmore\').hide();
        } else {
            $(\'.loadmore\').show();
        }
    });
    
});
因此,当我应用过滤器时,它会起作用,并显示校正结果。在没有任何过滤的页面加载中,loadmore功能可以正常工作。

但当我应用过滤器,然后单击“显示更多”时,不会显示任何结果。。

谢谢你的帮助!

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

您可以使用与WP Job Manager相同的方法来执行此操作:https://github.com/Automattic/WP-Job-Manager/blob/master/assets/js/ajax-filters.js

这是通过触发处理程序使查询定义;第“”页;查询应针对运行。我建议以它为例进行构建,因为它可以同时应用过滤器和不应用过滤器。

ALSO ALWAYS ALWAYS ALWAYS SANITIZE USER DATA您使用的任何位置$_POST $_GET $_REQUEST 等等,在任何地方使用数据之前,都应该对其进行清理。最好养成这样的习惯,否则坏事最终会发生。https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/

相关推荐

警告:第56行的主题php中为Foreach()提供的参数无效

我发现了这个错误,但不知道该怎么办,我已经禁用了插件并再次激活了它们,但每个产品的评论页面上都显示了相同的错误。非常感谢你的帮助下面是确切的错误:警告:在/home/flowt/public\\u html/wp-content/themes/rubens/template/single-product/u-review中为foreach()提供的参数无效。php在线56所以我去了我的主题编辑器,下面是我在第56行看到的内容,但不确定我是否应该触摸这段代码,我不是一个程序员:printf(\'<di