Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Detect the last post in the WordPress loop
<?php if (($wp_query->current_post +1) == ($wp_query->post_count)) {
echo 'This is the last post';
} ?>
<?php if (($wp_query->current_post +1) != ($wp_query->post_count)) {
echo 'This is the not the last post';
} ?>
@ronaldaraujo
Copy link

ronaldaraujo commented Oct 18, 2016

+1

@alexandremaeda
Copy link

alexandremaeda commented Mar 2, 2017

+1

@ottobyte
Copy link

ottobyte commented Mar 30, 2017

+1

@sinashamsizadeh
Copy link

sinashamsizadeh commented Aug 13, 2017

+1

@jemoreto
Copy link

jemoreto commented Aug 24, 2017

+1

@bloolight
Copy link

bloolight commented Jan 25, 2018

+1

@pareshsojitra
Copy link

pareshsojitra commented Mar 14, 2018

+1

@dev-hero
Copy link

dev-hero commented Mar 29, 2018

+1

@StevenCombes
Copy link

StevenCombes commented Apr 26, 2018

+1

@acenkus
Copy link

acenkus commented May 1, 2018

+1

@nr1q
Copy link

nr1q commented May 15, 2018

+1

@irwinbraganza
Copy link

irwinbraganza commented Jun 21, 2018

+1

@ronjramos
Copy link

ronjramos commented Nov 20, 2018

+1

@RaiBrightfox
Copy link

RaiBrightfox commented Dec 17, 2018

+1

@manuelricci
Copy link

manuelricci commented Feb 21, 2019

+1

@jamiecalabro
Copy link

jamiecalabro commented Mar 1, 2019

+1

@chpruckner
Copy link

chpruckner commented Mar 7, 2019

Thank you so much!!
+1

@harnerdesigns
Copy link

harnerdesigns commented Mar 25, 2019

Nice 👍

@imomer
Copy link

imomer commented Apr 11, 2019

+1

@rainb3rry
Copy link

rainb3rry commented Jun 21, 2019

or,
if (!previous_post_link()) { echo 'the first post here'; }
if (!next_post_link()) { echo 'the last post here'; }

@srikat
Copy link

srikat commented Jul 4, 2019

or,
if (!previous_post_link()) { echo 'the first post here'; }
if (!next_post_link()) { echo 'the last post here'; }

get_previous_post_link() and get_next_post_link() should be used instead for the if conditions.

@fearlex
Copy link

fearlex commented Sep 14, 2019

+1

@christianpornela
Copy link

christianpornela commented Sep 26, 2019

+1

@Rmanaf
Copy link

Rmanaf commented Aug 18, 2020

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment