I have Googled for a while and I am not sure how is the best way to do this.
In wp-includes/general-template.php
I am looking at the function wp_get_archives()
which has this line of code in:
$where = apply_filters( 'getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
What I want to do is have:
$where = apply_filters( 'getarchives_where', "WHERE post_type = 'post' OR post_type = 'events' AND post_status = 'publish'", $r );
However I am not sure how to hook into this filter and override it in functions.php
Any advice appreciated.
Thanks,
Ian
A WordPress filter is a function that takes in a string, array, or object, does something to it, and returns that filtered string, array, or object.
So what you want to do is turn
"WHERE post_type = 'post' AND post_status = 'publish'"
into"WHERE post_type = 'post' OR post_type = 'events' AND post_status = 'publish'"
. That is fairly straightforward.From the looks of things, the
getarchives_where
filter accepts two arguments. So you’ll hook onto the filter like so:Then you need to write a function that takes in two parameters, filters them, and returns a string:
Now, this function will take in any input, but it will always return the string for the filter you specified. There are much more advanced ways to add query parameters, but this will accomplish exactly what your question is asking.
In a plugin or in your themeâs
functions.php
just write:That is better than a custom
WP_Query
in my opinion, and you donât even need to accept any parameters in your callback because you donât use theme. 🙂To understand how filters work read the Codex on the Plugin API. Basically, your callback return value will replace the second part in
apply_filters()
.What you’ll actually want to do is use the built-in WordPress class called
WP_Query
. This way you won’t be changing the actual WordPress core functionality (which would give yourself major headaches when it’s time to upgrade).In your archives page, replace your current loop with a custom query like so:
The
$args
array is simply your custom logic of which posts should show up inside this loop. See the WP_Query documentation for a full list of things you can put into this array.For example, you want to filter on post type, so see this section of the document and you will notice that you can build your
$args
array like so:Hope that helps!
[edit]
I just realized that you might be wanting to obtain a simple unordered list of posts in the archive (and not necessarily display the posts themselves, since that’s actually how
wp_get_archives
behaves).Simply build your own unordered list by wrapping the loop in a
<ul>
tag and then inside the loop output<li>
tags around the title of the archived post and the permalink to the archived post.