Created
June 1, 2021 13:12
-
-
Save Prroffessorr/8f0a69bbc56dfc05b3a9b1a695cfc927 to your computer and use it in GitHub Desktop.
AJAX Загрузка постов по скролу. WordPress (Примечание: для корректной работы wp_localize_script, необходимо чтобы у вас был подключен wp_head()). Иначе будут ошибки
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$posts_id = 3; //получаем id рубрики. Любым удобным способом | |
$count_of_posts = 2; //кол-во выводимых элементов | |
$paged = get_query_var('paged', 1);//Получаем текущую страницу | |
if(!empty($id)){ | |
$get_posts = new WP_Query( "category__in=$posts_id&posts_per_page=$count_of_posts&paged=$paged" ); | |
} | |
else{ | |
$get_posts = new WP_Query( "category__in=1&posts_per_page=$count_of_posts&paged=$paged" ); | |
} ?> | |
<ul class="list" id="posts_list"> | |
<?php | |
while ($get_posts->have_posts()): | |
$get_posts->the_post(); ?> | |
<li><?php echo the_title(); ?></li> | |
<?php | |
endwhile; ?> | |
</ul> | |
<?php | |
//Скрытое поле с параметрами для запроса | |
echo '<div hidden="true" class="load_more_param" name="'.$posts_id.','.$count_of_posts.','.$get_posts->max_num_pages.'"></div>'; | |
?> | |
<!--Прелоадер--> | |
<div class="wrapper" id="loader_id"> | |
<h3>Card content loader</h3> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Подключаем скрипт автоматической загрузки на постов | |
function misha_my_load_more_scripts() { | |
// In most cases it is already included on the page and this line can be removed | |
wp_enqueue_script('jquery'); | |
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') ); | |
wp_localize_script( 'my_loadmore', 'load_more_param', array( | |
'ajaxurl' => admin_url( 'admin-ajax.php' ), | |
) ); | |
wp_enqueue_script( 'my_loadmore' ); | |
} | |
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts',100 ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Фунцкия обработки AJAX запроса на зугрузку постов | |
function loadmore_ajax_function(){ | |
//Формируем запрос в БД исходя из полученных данных | |
$params = array( | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
'orderby' => 'date', | |
'order' => 'DESC', | |
'posts_per_page' => $_POST['postPerPage'], | |
'paged' => $_POST['pageNumber'], | |
'category__in' => array($_POST['category']) | |
); | |
$query = new WP_Query($params); | |
while ($query->have_posts()): | |
$query->the_post(); ?> | |
<li><?php the_title() ?></li> | |
<?php | |
endwhile; | |
wp_reset_postdata(); | |
die; | |
} | |
add_action('wp_ajax_ajax_loadmore', 'loadmore_ajax_function'); // wp_ajax_{action} | |
add_action('wp_ajax_nopriv_ajax_loadmore', 'loadmore_ajax_function'); // wp_ajax_nopriv_{action} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(function($){ | |
var pageNumber = 2, //Передаем начальную страницу | |
canBeLoaded = true, //Параметр нужен для начала загрузки новых постов | |
bottomOffset = 2000; //Дистаниция в пикселях, с которой мы хотим начинать загружать новые посты | |
$(window).scroll(function(){ | |
//Сохраняем параметры загрузкика в одну переменную | |
var params = $(document.getElementsByClassName("load_more_param")).attr("name"); | |
//Разделяем все параметры | |
const param = params.split(","); | |
var data = { | |
'action': 'ajax_loadmore', | |
'category': param[0], //Идентификатор | |
'postPerPage': param[1], //Количество постов в одном запросе | |
'pageNumber': pageNumber | |
}; | |
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){ | |
$.ajax({ | |
url : load_more_param.ajaxurl, | |
data:data, | |
type:'POST', | |
//Перед загрузкой показываем прелоадер | |
beforeSend: function(){ | |
if(pageNumber<=param[2]){ //param[2] - общее число страниц | |
document.getElementById("loader_id").style.visibility = "visible"; | |
} | |
canBeLoaded = false; | |
}, | |
success:function(data){ | |
if( data ) { | |
posts_list.innerHTML += data; | |
pageNumber++; | |
document.getElementById("loader_id").style.visibility = "hidden"; | |
canBeLoaded = true; // Если все хорошо, мы можем запускать процес заново | |
} | |
} | |
}); | |
} | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment