I have a page with two sections, each uses a different WP_Query()
to pull in events
, which are a custom post type. Each WP_Query()
queries a meta_key
for the event date so that Section 1 only displays upcoming events
and Section 2 displays past events
.
The upcoming events
in Section 1 display all relevant information on my page, so clicking them is not possible.
The past events
in Section 2 only display the event
title and are clickable. When users click a past event
they link to a custom single-event.php
template for the past event
.
I want to display Previous/Next navigation in the single-event.php
template, but the navigation should only point to past events
.
I tried using next_post_link()
and previous_post_link()
but these will link to upcoming events
too, which I do not want. I can probably setup a new WP_Query()
on my single-event.php
and loop through it to get the Prev/Next IDs, but repeating the query seems like a drastic step.
I would really appreciate some insight on a way to filter out upcoming events
from my Previous/Next post links. I’ve seen this question but I would prefer not to use a plugin.
I managed to get this working using nothing but WordPress filters, thanks to @Milo’s hint.
Just note that these are pretty specific to my case but you shouldn’t have a problem modifying them for your own use. I am using Advanced Custom Fields with a Date Picker field called
date
and Prev/Next links only point to events withdate
fields set to any day before today.I created 5 filters:
JOIN
(to addwp_postmeta
)WHERE
for the Previous linkWHERE
for the Next linkSORT
for the Previous linkSORT
for the Next linkHere’s what I came up with, it seems to be working but if anyone spots any issues I would love feedback:
i had a pretty similar problem, needed to sort and exclude several posts from prev/next navigation. problem with @cfx’s solution was: its not capable for ajax: the
is_singular()
function returns false, if you load contents via wp-ajax. so it worked on page load, but didn’t, when content was changed by ajax.global $post;
was helping me out here.here is my solution:
in this case, the costum field query is: exclude all posts, that have cf
not_clickable
set totrue
.another problem i encountered: i had some content created and then implemented that custom field afterwards.. so the query also excluded the posts that didn’t even had that field attached to the post, no matter if true or false. just keep that in mind, when using this type of filtering. make sure that every post has a value or consider this in your sql syntax..