Query latest post from each category

Multi tool use


Query latest post from each category
I know there are quite a few questions about wp_queries but none are quite answering what I want.
I was wrecking my brain on how to query 1 most recent post from each of my blog categories but using the notation instead of an array:
function get_latest_posts($query_args, $grid_name) {
$categories = array(1593, 1594, 1595, 1596, 1597);
if ($grid_name == 'get_latest_posts') {
$query_args['posts_per_page'] = 1;
}
return $query_args;
}
add_filter('tg_wp_query_args', 'get_latest_posts', 10, 2);
// This returns one post but just one post, not one post per category
Using this style of query_args instead of a "traditional" array, would it be possible to have something like:
foreach($categories as $category) {
return $query_args;
}
// Something like this would be awesome ❥
Thank you in advance! Sorry I'm such a newbie.
[1593]
['category' => 1593]
The ['key'] => value one! Sorry for not clarifying.
– Tudor
yesterday
You loop through associative arrays with
foreach
like you posted. If you want to generate a list of the first post of every category before outputting, then you'll have to put everything inside your own associative array before using return
. You should only return
after the foreach is done looping through each category by putting return
it after the foreach
. Your return value can be your associative array.– JM-AGMS
yesterday
foreach
return
return
return
foreach
1 Answer
1
Try this:
<?php
function post_from_each_category(){
$categories = array(1593, 1594, 1595, 1596, 1597);
$posts = ;
foreach($categories as $category) {
$posts = get_posts([
'post_type' => 'post',
'posts_per_page' => 1,
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => [$category],
],
],
]);
}
return $posts;
}
I think it will solve your problem.
Thank you so much for taking the time. I modified the code a little bit to work with "The Grid" plugin (added the if grid name statement), but it doesn't seem to want to work, and I am a little confused as how I could test or get some kind of output of what I am doing wrong.
– Tudor
yesterday
no problem sir...
– Paras
yesterday
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
There are two different types of arrays, but both are still arrays.
[1593]
(array) and['category' => 1593]
(associative array). Which are you talking about?– JM-AGMS
yesterday