Documentation / Tutorials / Tutorials & How to’s
How to get next or previous post given a post id in WordPress
/ Tutorials & How to’s / How to get next or previous post given a post id in WordPress
Here is a quick code sample to get next and/or previous post of WordPress post if you have the post id using Awesome Studio.
[aw2.get prev_post post_id='{post.ID}' set='module.prev_post_id' /] [aw2.get next_post post_id='{post.ID}' set='module.next_post_id' /] [aw2.set module.prev_post=''/] [aw2.query get_post post_id='{module.prev_post_id}' set='module.prev_post' not_empty='{{aw2.get module.prev_post_id}}' /] [aw2.set module.next_post=''/] [aw2.query get_post post_id='{module.next_post_id}' set='module.next_post' not_empty='{{aw2.get module.next_post_id}}' /] [aw2.template next_post_t] [aw2.if cond="{{aw2.get module.next_post}}" not_equal=""]col-sm-offset-1 col-sm-5[/aw2.if] [/aw2.template] [aw2.template prev_post_t] [aw2.if cond="{{aw2.get module.prev_post}}" not_equal=""]col-sm-5[/aw2.if] [aw2.if cond="{{aw2.get module.prev_post}}" equal=""]col-xs-offset-1[/aw2.if] [/aw2.template] [aw2.if cond="{{aw2.get module.prev_post}}" not_equal=""] [aw2.client style] div.col-xs-offset-1.pag-next{ border:0; } [/aw2.client] [/aw2.if] [aw2.if cond="{{aw2.get module.prev_post }}" not_equal=""] <div class="col-xs-offset-1 col-xs-10 [aw2.run templates.next_post_t /] pag-prev" data-matchheight='[aw2.get module.post_unique_class]'> <p class='text-center'> <span class='font-size-smaller gray-light text-uppercase'>Previous Post</span> <br /> <a href="[aw2.get module.prev_post.url /]" class='font-size-larger gray-darker'>[aw2.get module.prev_post.post_title /]</a> </p> </div> [/aw2.if] [aw2.if cond="{{aw2.get module.next_post}}" not_equal=""] <div class="col-xs-10 [aw2.run templates.prev_post_t /] pag-next" data-matchheight='[aw2.get module.post_unique_class]'> <p class='text-center'> <span class='font-size-smaller gray-light text-uppercase'>Next Post</span> <br /> <a href="[aw2.get module.next_post.url /]" class='font-size-larger gray-darker'>[aw2.get module.next_post.post_title /]</a> </p> </div> [/aw2.if]
- Given a post_id you can get the next & prev post using prev_post & next_post as shown in line 1 & 2 above.
- Line 5 & 9 is used to get the actual post object from the post_id we got from line 1 & 2
- Template next_post_t and prev_post_t are used to handle the situations when we are on first or last post.
- 29 -39 & 41-50 is basically used to show the title of the next and previous post.