Добавление кнопки загрузки больше с моей главной страницы на мою страницу поиска
На моей первой странице у меня есть мои сообщения, созданные как 1 сообщение в строке, 2 строки по 2 сообщения в строке, 1 сообщение в строке и т.д. Затем после каждых 15 сообщений появляется кнопка загрузки большего количества (пример ниже). Кнопка загрузки больше работает отлично, поэтому я пытаюсь дублировать ее на моей странице поиска.
Я хотел бы добавить ту же самую кнопку загрузки больше на мою страницу поиска. Тем не менее, у меня есть мои сообщения, настроенные по-разному на этой странице, у меня всего 2 сообщения в каждой строке (нет чередующейся почты col-12). В дополнение к другой структуре цикла я хотел бы добавить кнопку загрузки больше после каждых 8 сообщений (пример ниже). Я продублировал структуру цикла для своей главной страницы в моем functions.php и скорректировал ее, чтобы соответствовать другой структуре цикла и кнопке загрузки больше после каждых 8 сообщений. Однако это будет работать неправильно. Первые 8 сообщений показывают, как я их хочу, 4 строки по 2 столбца в строке. Но после того, как вы нажмете кнопку "Нагрузка больше", сообщения отображаются так же, как и в моей первой странице (15 сообщений из 1 сообщения в строке, 2 строки по 2 столбца в строке, 1 сообщение в строке и т.д.),
Кто-нибудь знает, как я могу это исправить? Или найти страницу поиска из 4 строк с 2 сообщениями в строке? Спасибо заранее.
как выглядит моя лицевая страница
![введите описание изображения здесь]()
как я хочу, чтобы страница поиска выглядела
![введите описание изображения здесь]()
my front-page.php
<?php
get_header();
get_template_part ('post-template/trendingg');
?>
<script>
var now=2; // when click start in page 2
jQuery(document).on('click', '#load_more_btn', function () {
jQuery.ajax({
type: "POST",
url: "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data: {
action: 'my_load_more_function', // the name of the function in functions.php
paged: now, // set the page to get the ajax request
posts_per_page: 15 //number of post to get (use 1 for testing)
},
success: function (data) {
if(data!=0){
jQuery("#ajax").append(data); // put the content into ajax container
now=now+1; // add 1 to next page
}else{
jQuery("#load_more_btn").hide();
}
},
error: function (errorThrown) {
alert(errorThrown); // only for debuggin
}
});
});
</script>
<section id="ajax"><!-- i have to change div to section, maybe a extra div declare -->
<?php
$the_query = new WP_Query( [
'posts_per_page' => 15, // i use 1 for testing
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => get_query_var('paged', 1) //page number 1 on load
] );
if ($the_query->have_posts()) {
$i = 0;
$j = 0;
while ($the_query->have_posts()) {
$the_query->the_post();
if ( $i % 5 === 0 ) { // Large post: on the first iteration and every 7th post after... ?>
<div class="row">
<article <?php post_class( 'col-sm-12 col-md-12' ); ?>>
<div class="large-front-container">
<a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?></a>
</div>
<div class="front-page-date"><?php echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'); ?></div>
<div class="front-page-post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'includes/front-shop-the-post' ); ?>
<?php get_template_part( 'includes/share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
</div>
<?php } else { // Small posts ?>
<?php if($j % 2 === 0){ echo '<div class="row">';} ?>
<article <?php post_class( 'col-sm-6 col-md-6' ); ?>>
<div class="two-front-container">
<a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?></a>
<div>
<div class="front-page-date"><?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?></div>
<div class="front-page-post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'includes/front-shop-the-post' ); ?>
<?php get_template_part( 'includes/share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
<?php $j++; if($j % 2 === 0){ echo '</div>';}?>
<?php
}
$i++;
}?>
<?php
}?>
</section>
<button id="load_more_btn">Load More Posts</button> <!-- button out of ajax container for load content and button displayed at the bottom -->
<?php
get_footer();
Ответы
Ответ 1
Сначала вы должны выполнить свой вызов ajax и задать значение поиска.
от search.php
замените свой стартовый код на:
var now=2; // when click start in page 2
var searchValue = <?php echo json_encode(['s' => $s]); ?>;
jQuery(document).on('click', '#load_more_btn', function () {
jQuery.ajax({
type: "POST",
url: "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data: {
action: 'my_load_more_function_s', // the name of the function in functions.php,
s: searchValue.s, // the value from the input
paged: now, // set the page to get the ajax request
posts_per_page: 8, //number of post to get (use 1 for testing)
},
закодировать переменную s
с помощью json_encode
И затем измените вашу функцию ajax следующим образом:
function my_load_more_function_s() {
global $query_string;
$search_query = wp_parse_str( $query_string );
$search = array_merge($search_query, [
'posts_per_page' => $_POST["posts_per_page"],
'orderby' => 'post_date', 'order' => 'DESC',
'paged' => get_query_var('paged', $_POST["paged"]),
's' => $_POST['s']
]);
$query = new WP_Query($search);
s
-параметр можно найти в docs.
Подробнее о странице поиска. Я обнаружил, что вы должны использовать global $query_string
. Вы можете найти это в docs тоже
Для этого не забудьте, что вы можете сохранить число в php и выводить для javascript, например:
data: {
action: 'my_load_more_function', // the name of the function in functions.php
paged: now, // set the page to get the ajax request
posts_per_page: <?php echo $number; ?> //number of post to get (use 1 for testing)
}