Добрый день!
Нашел мануал
https://rudrastyh.com/wordpress/ajax-load-more-wit...
задача на главной странице сделать вывод новостей с фильтрацией по категориям и возможностью погрузке новых новостей
У Михаила в фильтрах участвуют в фильтрах формы, я немного переделал.
в общем к кодам:
Код которой стоит на главной странице:
<div id="filters">
<?php
if( $terms = get_terms( array(
'taxonomy' => 'category', // to make it simple I use default categories
'orderby' => 'name',
'include' => '20,33,32,34',
'hide_empty' => false
) ) ) :
// if categories exist, display the dropdown
echo '<a href="#" id_category="20,33,32,34">Все</a>';
foreach ( $terms as $term ) :
echo '<a href="#" id_category="' . $term->term_id . '">' . $term->name . '</a>'; // ID of the category as an option value
endforeach;
endif; ?>
</div>
<?php
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
// WP_Query arguments
$args = array (
'post_type' => array( 'post' ),
'post_status' => array( 'publish' ),
'paged' => $paged,
'cat' => 20,33,32,34
);
// The Query
query_posts( $args );
?>
<div class="row home-posts filter-df">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
?>
<div class="item_new_filter">
<div class="blogimage">
<a href="<?php the_permalink();?>" class="blogimagelink"><?php if ( has_post_thumbnail() ) {
the_post_thumbnail( 'louis-blog-thumb', array( 'class' => 'louis-featured-image' ) );
} else { ?>
<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/default.gif" alt="<?php the_title_attribute(); ?>" />
<?php } ?><i class="fa fa-chevron-right"></i></a>
</div><!-- Blogimage -->
<h3 class="blogposttitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p class="blogpostmeta"><i class="fa fa-calendar"></i> <a href="<?php the_permalink(); ?>"><?php the_time( get_option( 'date_format' ) ); ?></a></p>
</div><!-- end col-1-3 -->
<?php endwhile;?>
<?php
if ( $wp_query->max_num_pages > 1 ) :
echo '<div id="yoon_loadmore">Ещё</div>'; // you can use <a> as well
endif;
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
</div>
код обработки ajax запроса, для него создал плагин.
add_action( 'wp_enqueue_scripts', 'yoon_script_and_styles');
function yoon_script_and_styles() {
// absolutely need it, because we will get $wp_query->query_vars and $wp_query->max_num_pages from it.
global $wp_query;
// when you use wp_localize_script(), do not enqueue the target script immediately
wp_register_script( 'yoon_scripts', plugins_url( 'filter-d.js', __FILE__ ), array( 'jquery' ) );
// passing parameters here
// actually the <script> tag will be created and the object "misha_loadmore_params" will be inside it
wp_localize_script( 'yoon_scripts', 'yoon_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
) );
wp_enqueue_script( 'yoon_scripts' );
}
add_action('wp_ajax_loadmorebutton', 'yoon_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmorebutton', 'yoon_loadmore_ajax_handler');
function yoon_loadmore_ajax_handler(){
// prepare our arguments for the query
$params = json_decode( stripslashes( $_POST['query'] ), true ); // query_posts() takes care of the necessary sanitization
$params['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$params['post_status'] = 'publish';
// it is always better to use WP_Query but not here
query_posts( $params );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
require plugin_dir_path( __FILE__ ) . 'tpl-fd.php';
endwhile;
endif;
die; // here we exit the script and even no wp_reset_query() required!
}
add_action('wp_ajax_yoonfilter', 'yoon_filter_function');
add_action('wp_ajax_nopriv_yoonfilter', 'yoon_filter_function');
function yoon_filter_function(){
$link = ! empty( $_POST['data'] ) ? esc_attr( $_POST['data'] ) : false;
echo $link;
if ( ! $link ) {
die( 'Рубрика не найдена' );
}
$params = array(
'posts_per_page' => $_POST['yoon_number_of_results'], // when set to -1, it shows all posts
'post_status' => 'publish',
'cat' => $link
);
query_posts( $params );
global $wp_query;
if( have_posts() ) :
ob_start(); // start buffering because we do not need to print the posts now
while( have_posts() ): the_post();
require plugin_dir_path( __FILE__ ) . 'tpl-fd.php';
endwhile;
$posts_html = ob_get_contents(); // we pass the posts to variable
ob_end_clean(); // clear the buffer
else:
$posts_html = '<p>Nothing found for your criteria.</p>';
endif;
// no wp_reset_query() required
echo json_encode( array(
'posts' => json_encode( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'found_posts' => $wp_query->found_posts,
'content' => $posts_html
) );
die();
}
Js код
Query(document).ready(function ($) {
$('#yoon_loadmore').click(function(){
$.ajax({
url : yoon_loadmore_params.ajaxurl, // AJAX handler
data : {
'action': 'loadmorebutton', // the parameter for admin-ajax.php
'query': yoon_loadmore_params.posts, // loop parameters passed by wp_localize_script()
'page' : yoon_loadmore_params.current_page // current page
},
type : 'POST',
beforeSend : function ( xhr ) {
$('#yoon_loadmore').text('Загрузка...'); // some type of preloader
},
success : function( posts ){
if( posts ) {
$('#yoon_loadmore').text( 'Ещё' );
$('.filter-df').append( posts ); // insert new posts
yoon_loadmore_params.current_page++;
if ( yoon_loadmore_params.current_page == yoon_loadmore_params.max_page )
$('#yoon_loadmore').hide(); // if last page, HIDE the button
} else {
$('#yoon_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
/*
* Filter
*/
$('#filters a').click(function (e){
e.preventDefault();
var linkCat = $(this).attr('id_category');
console.log(linkCat);
$.ajax({
url : yoon_loadmore_params.ajaxurl,
data : linkCat, // form data
dataType : 'json', // this data type allows us to receive objects from the server
type : 'POST',
beforeSend : function(xhr){
$('#filters').find('a').text('Filtering...');
},
success : function( data ){
// when filter applied:
// set the current page to 1
yoon_loadmore_params.current_page = 1;
// set the new query parameters
yoon_loadmore_params.posts = data.posts;
// set the new max page parameter
yoon_loadmore_params.max_page = data.max_page;
// change the button label back
$('#filters').find('a').text('hhh');
// insert the posts to the container
$('.filter-df').html(data.content);
// hide load more button, if there are not enough posts for the second page
if ( data.max_page < 2 ) {
$('#yoon_loadmore').hide();
} else {
$('#yoon_loadmore').show();
}
}
});
// do not submit the form
return false;
});
});
ну и на всякий случай шаблон который использую в цикле
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
?>
<div class="item_new_filter">
<div class="blogimage">
<a href="<?php the_permalink();?>" class="blogimagelink"><?php if ( has_post_thumbnail() ) {
the_post_thumbnail( 'louis-blog-thumb', array( 'class' => 'louis-featured-image' ) );
} else { ?>
<img src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/default.gif" alt="<?php the_title_attribute(); ?>" />
<?php } ?><i class="fa fa-chevron-right"></i></a>
</div><!-- Blogimage -->
<h3 class="blogposttitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p class="blogpostmeta"><i class="fa fa-calendar"></i> <a href="<?php the_permalink(); ?>"><?php the_time( get_option( 'date_format' ) ); ?></a></p>
</div><!-- end col-1-3 -->
<?php endwhile;?>
<?php
if ( $wp_query->max_num_pages > 1 ) :
echo '<div id="yoon_loadmore">More posts</div>'; // you can use <a> as well
endif;
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>
Почему то ничего не работает.
Хотя и по ошибке пишет что 403, а по мануалу с WP-kama все работало, но не коректно работала пагинация.
подскажите гуру где я накосячил
на $('#filters').find('a').text('hhh'); - не обращайте внимания
Благодарю вас!