The need: I'm trying to filter a custom post type archive using a GET parameter, so that I can split the posts in two groups depending on which terms they are tagged with.
How: So far I've decided to use the pre_get_posts
hook, altering the query when the archive for this custom post type is rendered.
The problem: The code I'm using is not working. I can't seem to find the issue, but it is definitely not working. Maybe someone who has more exp with this hook may tell me what I'm missing:
function event_type_filter( $query ) {
if ( is_post_type_archive( 'event' ) ) {
if ( isset($_GET["event_term"]) ) {
$tipo_de_curso = $_GET["event_term"];
if ( $tipo_de_curso == "singleclass" ) {
$query->set( 'cat', '1,2,3,4' );
}
if ( $tipo_de_curso == "course" ) {
$query->set( 'cat', '-1,-2,-3,-4' );
}
}
}
return $query;
}
add_action('pre_get_posts','event_type_filter');
Here in the Codex they recommend a similar approach, and I can't spot the differences, but sure there has to be some. There is some questions in this site about this hook that should serve as a model, but I didn't see how to adapt to my case.
Any ideas? Thanks :)
return $query;
?if ( is_post_type_archive('event') && ! empty( $query->query['post_type'] == 'event' )
return $query;
does not have an effect, but neither had the addition, to begin with. (I already tried with and without it.). Also, I completed theif
statement, but I cant notice any changes. Thanks @Reigelis_post_type_archive()
may fail - See the Notes section in the Codex. Perhaps replaceif(is_post_type_archive('event'))
withif(get_query_var('event'))
?add_action()
), the function that you reference doesn't need to return anything. On the other hand, if you are using a filter hook (add_filter()
) then you do need to return a value. So in your case the linereturn $query;
is superfluous - it's not causing your code to fail, but you don't need it.