I want to sort posts by a meta value in a custom field. Basically I've added a field called 'date_event' and want to sort the posts by that date (stored as YYYYMMMDD).
The only working example I have is this placed in the loop.php:
$query = new WP_Query(
array(
'meta_key' => 'date_event',
'orderby' => 'meta_value_num',
'order' => 'DESC',
)
);
This does the trick by sorting, but it takes all posts and sorts them no matter what category I'm viewing. From what I can see it's because I've called the $query
again and not 'filtering' the posts I guess. It might also just be bad coding.
Anyway my goal is to have the posts sorted but only display the posts that are in that category you are in.
Any tips or references are greatly appreciated.
I want to sort posts by a meta value in a custom field. Basically I've added a field called 'date_event' and want to sort the posts by that date (stored as YYYYMMMDD).
The only working example I have is this placed in the loop.php:
$query = new WP_Query(
array(
'meta_key' => 'date_event',
'orderby' => 'meta_value_num',
'order' => 'DESC',
)
);
This does the trick by sorting, but it takes all posts and sorts them no matter what category I'm viewing. From what I can see it's because I've called the $query
again and not 'filtering' the posts I guess. It might also just be bad coding.
Anyway my goal is to have the posts sorted but only display the posts that are in that category you are in.
Any tips or references are greatly appreciated.
If you are on a category page (that is at URL like https://example/cateogry/test/ and want to filter your query by "test" category) then you can modify your code to this
global $wp_query;
$query = new WP_Query(
array(
'meta_key' => 'date_event',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'advert_category',
'field' => 'term_id',
'terms' => $wp_query->get_queried_object_id(),
),
)
)
);
This will of course work only if you will run this query once the WP request is parsed and executed, in other words it will work if you run this code after "wp" action.
If you want to add this code in your theme template files then it should work fine.
The way WP Query works is by creating an entirely new query to the database.
WP_Query
Apart from 'orderby' you would also need to assign value to the category parameter as well. Now, depending if these are regular posts or a custom post type, you would need to assign values to different parameters.
The other important part here is that you need to know the current category you are viewing (This would only work on a category page template). The easiest way is to call get_queried_object_id()
.
$args = array(
'meta_key' => 'date_event',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'cat' => get_queried_object_id(),
);
$cust_query = new WP_Query($args);