I have category 'news' http://localhost/foldername/news
, for each 'news' posts I have custom field called 'years' and is set up as a Text Field. I have 2 values assigned n different posts '2013' and '2014'.
What I'm trying to do first to show only 2014 posts in 'news' category http://localhost/foldername/news
and second to pass url parameter so if I want to show '2013' to use the following http://localhost/foldername/news/?years=2013
I have selected Attribute so user will select which year posts to show but as default will show 2014 posts
<select>
<option value="2014">2014</option>
<option value="2013">2013</option>
</select>
For the first I found the following solution to show only '2014' posts in 'news' http://localhost/foldername/news
:
$args= array(
'meta_key' => 'years',
'meta_value' => '2014',
);
query_posts($args);
Now my big problem is that I pass the parameter to show '2013' posts but is not working
Tried something like this:
function wpse129223_custom_meta_query( $query ) {
// If not on the main query, or on an admin page, bail here
if ( ! $query->is_main_query() || is_admin() ) {
return;
}
// If 'type' isn't being passed as a query string, bail here
if ( empty( $_GET['years'] ) ) {
return;
}
// Get the existing meta query, cast as array
$meta_query = (array) $query->get('meta_query');
// Convert 'type' into an array of types
$types = explode( ',', $_GET['years'] );
// Ensure that types aren't empty
if ( is_array( $types ) && ! empty( $types ) ) {
// Build a meta query for this type
$meta_query[] = array(
'key' => 'years',
'value' => $types,
'compare' => 'IN',
);
// Update the meta query
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'wpse129223_custom_meta_query' );
But every time I go to http://localhost/foldername/news/?years=2013
still shows me '2014' posts
query_posts($args);
running? If so remove that. Then in yourpre_get_posts
do a check foris_category( 'news' )
at the top. Then set the default years to "2014" by removing the check onempty( $_GET...
and using$types = explode( ',', empty( $_GET['years'] ) ? "2014" : $_GET['years'] );