В настоящее время я сталкиваюсь с некоторыми проблемами с моей функцией, которая загружает больше сообщений на моем сайте.Как видите, по умолчанию отображаются последние четыре сообщения в правильном порядке.Однако, когда я нажимаю кнопку «загрузить больше», он показывает больше сообщений, но затем складывается в случайном порядке.
Я боролся с этим уже почти два дня, пробовал все, с чем сталкивался, и также получил помощь от моего друга, который на самом деле является опытным разработчиком WordPress, и он так и не нашел решения.
Я провел небольшое исследование и попытался добавить 'suppress_filters' = true
без какой-либо удачи.Итак, вот мой код.
Этот код отображает четыре сообщения по умолчанию в правильном порядке:
<section class="posts-container">
<div class="container">
<h1 class="earlier-posts-title mt-5 text-center"><?php echo get_theme_mod('earlier_posts_title'); ?></h1>
<div class="container-fluid">
<div class="row mt-5 mb-5 misha_posts_wrap">
<?php if(have_posts()) : ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="col-lg-6 mb-4">
<?php if(has_post_thumbnail()): ?>
<div class="thumbnail-container">
<?php the_post_thumbnail('', array('class' => 'thumbnail-post')); ?>
</div>
<?php endif; ?>
<h1 class="thumbnail-title mt-3 text-center"><?php the_title(); ?></h1>
<p><?php echo the_time(); ?></p>
<div class="meta">
<p class="thumbnail-meta mt-3 text-center"><i class="far fa-clock"></i> Skrevet den <?php the_time('j. F Y');?></p>
</div>
<p class="thumbnail-content-text text-left"><b class="text-left"><?php the_excerpt();?></b></p>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php endif;?>
<?php
global $wp_query; // you can remove this line if everything works for you
if ( $wp_query->max_num_pages > 1 )
echo '<div class="misha_loadmore">More posts</div>'; // you can use <a> as well
?>
</div>
</div>
</div>
</section>
А вот myloadmore.js:
jQuery(function($){
$('.misha_loadmore').click(function(){
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
$.ajax({
url : misha_loadmore_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...');
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().before(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
}
}
});
});
});
И, наконец, что не менее важно, файл functions.php:
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');
// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );
// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'my_loadmore', 'misha_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' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler(){
// prepare our arguments for the query
$args = json_decode(stripslashes($_POST['query']),true);
$args['paged'] = $_POST['page'] + 1;
$args['post_type'] = 'post';
$args['order'] = 'DESC';
$args['orderby'] = 'date';
$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();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
echo '<div class="col-lg-6 mb-4">';
echo '<div class="thumbnail-container">';
the_post_thumbnail('', array('class' => 'thumbnail-post'));
echo '</div>';
echo '<h1 class="thumbnail-title mt-3 text-center">';
echo the_title();
echo '</h1>';
echo '<div class="meta">';
echo '<p class="thumbnail-meta mt-3 text-center"><i class="far fa-clock"></i> Skrevet den ';
echo the_time('j. F Y');
echo '</p>';
echo '</div>';
echo '<p class="thumbnail-content-text text-left"><b class="text-left">';
echo the_excerpt();
echo '</b></p>';
echo '</div>';
echo '</div>';
endwhile;
endif;
die;
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler');
Итак, согласно моему тезису, проблема заключается в файле misha_loadmore_ajax_handler в файле functions.php, потому что, как толькоЯ нажимаю кнопку «Загрузить еще», все сообщения сортируются в случайном порядке.И вы также можете видеть, что я применил многочисленные фильтры в попытке исправить это.Я просто хочу, чтобы он правильно отображался.
Код от Миши, ссылка здесь: https://rudrastyh.com/wordpress/load-more-posts-ajax.html
Я довольно новичок в разработке WordPress и PHP в целом.
Что я здесь не так делаю?Любая помощь будет принята с благодарностью.