If you have ever used Laravel, you have probably also used Blade. Blade is a simple and powerful template language provided with Laravel. Blade has many wonderful features but one of them, as it relates to WordPress, is how it works with a The Loop.
Normally in the WordPress loop you would set a variable outside of the while statement and increment int. This works fine, but i felt that I was messy.
At a minimum, I wanted to know the first post in the loop so that I could alter its presentation. Naturally adding the last posts in the loop would be a sinch.
After doing some digging into how have_posts()
works I realized that it was pulling from $wp_query
and since $wp_query
has everything that I needed it was just a matter of creating a couple of methods.
Lets start off by creating our basic class, name space it whoever you want.
class TheLoop
{
public $index = 0;
private $wp_query;
public function __construct()
{
global $wp_query;
$this->wp_query = $wp_query;
}
}
To keep things clean, I also added have_posts()
which is also where I incremented the post loop.
public function have_posts()
{
$this->iterate();
return $this->wp_query->have_posts();
}
Next up we have to increment the post loop, nothing crazy here.
private function iterate()
{
$this->index = $this->index + 1;
}
Now that we have recreated the have_posts()
method and are iterating the post index, we can modify our Loop by creating a new instance of TheLoop
and replacing have_posts()
with our new method.
$loop = new Axe\Core\TheLoop;
while ($loop->have_posts()) : the_post();
// Post Stuff
endwhile;
As you can probably tell, nothing much changed here. If you were to do nothing else, your site would function exactly as it did before. But we have done two things.
We moved now have an instance of $wp_query
and are iterating through the posts array tracking its current position.
Lets add two more methods first()
and last()
.
public function first()
{
return ($this->index == 1) ? true : false;
}
public function last()
{
return ($this->index == count($this->wp_query->posts)) ? true : false;
}
While these should be self-explanatory, first() checks to see if the index is equal to 1. last()
checks to see if the index is the same as the total posts count for the current page.
For example, if you had 95 posts and are showing 10 posts per page then the last index would be 10 on the first page while the last index on the final page would be 5.
Let’s create a very basic example.
$loop = new Axe\Core\TheLoop;
while ($loop->have_posts()) : the_post();
if($loop->first()){
// Do something special for the first post.
} else {
// The rest of the posts.
}
endwhile;
And that’s it!
If you want to check out the entire code have a look at my starter base theme called Axe and view full code for TheLoop.