I have a blog that shows 9
blogs posts per page, with each additional page of blog posts automatically added using the Infinite Ajax Scroll plugin.
Every time a blog post is successfully queried the $postCount
variable increases its count by 1
.
[...]
<body>
<div class="posts">
<?php
$postCount = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post(); $postCount++;
if ( $postCount % 9 == 0 ) :
// show featured blog posts
else :
// show standard blog posts
endif;
endif;
?>
</div> <!-- /posts -->
<script>
var ias = jQuery.ias({
container: '.posts',
item: 'article',
pagination: '.pagination',
next: '.next',
delay: 0,
negativeMargin: 1000
});
</script>
</body>
I'd like for the $postCount
variable to remember its count on the AJAX loaded pages as well. So, instead of resetting to 0
the next page of blog posts would start at 10
.
I understand why it's not working (variables are only local) and that I'll need to use something like sessions
or get
, but I don't know how to implement that.
I'm guessing I need to start a session
on my index.php page pass that along to my IAS plugin call...
Any help greatly appreciated. Thanks!
Follow up 1:
I've had some luck getting PHP sessions to work by starting the session in my functions.php
file
function init_session() {
session_start();
}
add_action( 'init', 'init_session', 1 );
...and adding the sessions to my file like so:
[...]
<body>
<div class="posts">
<?php
$postCount = 0;
if ( isset ( $_SESSION[ 'postCount' ] ) ) :
$postCount = $_SESSION[ 'postCount' ];
endif;
[...] // wp_query
$_SESSION['postCount'] = $postCount;
?>
</div> <!-- /posts -->
</body>
As it stands the $postCounter
keeps counting... So what was initially considered post 1
could be post 100
when the page is refreshed.
I'll need to workout the logic to destroy the session if it's the first post...
Any thoughts welcome. Thanks.