I have site on WP.
I’m using AJAX to show my posts. On click on ‘more’ button appears two more posts. And I’m trying to hide the button when all of the posts are shown. But something go wrong.
I don’t understand how to take posts count to JS (it’s another variant), because construction var posts_count = "<?php echo $posts_count; ?>
doesn’t work – it gives only string!
JS
$(function () {
var posts = 2; //posts shown
var posts_offset = 2;
$("#load-post").click(function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "/wp-admin/admin-ajax.php",
data: ({
action: 'loadMore',
posts_offset: posts_offset
}),
success: function (data) {
$('.news #content').append(data);
posts_offset += 2;
}
});
});
});
PHP
function loadMore() {
$posts_count = wp_count_posts()->publish;
$posts_offset = $_GET['posts_offset'];
// get your $_GET variables sorted out
// setup your query to get what you want
query_posts( array( 'posts_per_page' => 2, 'offset'=> $posts_offset ) );
// initialsise your output
$output = '';
// the Loop
while (have_posts()) : the_post();
?><div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
<div class="news-date">
<?php the_time($format = "j F Y") ?>
</div>
<div>
<h3><?php the_title() ?></h3>
<p><?php the_content() ?></p>
</div>
</div><?php
endwhile;
if ($posts_count - ($posts_offset + 2) <= 0) { ?>
<script>$("#load-more").hide();</script>
<?php }
// Reset Query
wp_reset_query();
die($output);
}
This code works, but doesn’t work the part of hiding the button
change your code as follows:
in
PHP
and in
JS
You are not
echo
ing the script part.And why you are not separating the javascript part from php? Would be more elegant if you handle the scripting logic from ajax. In php you are sending back some response if the condition is not met, then you handle the DOM manipulation from javascript.