Shibbir
Shibbir

Reputation: 2031

WordPress - How to get 1 latest post of 5 categories so the total post will be 5 Posts

I have this variable with 5 categories:

 $category_needed = implode( ', ', $category_needed );

Output is:

arts-entertainment, learning, news, real-estate, uncategorized

Now, I want to get only the 1 latest post of the above categories.

So the total posts will be 5 FROM the 5 latest post of 5 categories.

To do that my code is below:

   $category_needed = implode( ', ', $category_needed );
    $post_args = [
        'post_type' => 'post',
        'numberposts' => 5,
        'category' => [ $category_needed ]
    ];

But I see I have 2 posts of same category which I don't want.

Is there any work arount?

Update:

echo '<pre>';
    print_r( $category_needed );
echo '</pre>';

Return:

Array
(
    [0] => 4
    [1] => 6
    [2] => 2
    [3] => 5
    [4] => 1
)

$latest_posts = array();

foreach ( $category_needed as $cat_id ){  // $category_ids is array of category ids
    $post_args = array(
        'post_type' => 'post',
        'numberposts' => 1,
        'category' => $cat_id,
    );
    $latest_post_of_category = get_posts( $post_args );
    $latest_posts[] = $latest_post_of_category[0];
}

foreach ( $latest_posts as $latest_post ) {
    $cat = get_the_category( $latest_post->ID);
    echo '<pre>';
        print_r( $cat[0]->name );
    echo '</pre>';
}

Now, it returns:

Arts & Entertainment
Learning
Learning
Real Estate
Real Estate

It's should be unique category, right?

Upvotes: 0

Views: 45

Answers (1)

user13046635
user13046635

Reputation:

There is no option to get only 1 post from every categories.

You need to get latest post in each categories within foreach block of category.

$latest_posts = array();
$exclude_post_ids = array(); // Added
foreach ( $category_ids as $cat_id ){  // $category_ids is array of category ids
    $post_args = array(
        'post_type' => 'post',
        'numberposts' => 1,
        'category' => $cat_id,
        'exclude' => $exclude_post_ids, // Added
    );
    $latest_post_of_category = get_posts( $post_args );
    $latest_posts[] = $latest_post_of_category[0];
    $exclude_post_ids[] = $latest_post_of_category[0]->ID; // Added

    echo '<pre>';
        print_r( get_cat_name( $cat_id ) . $latest_post_of_category[0]->post_title );
    echo '</pre>';
}

I added some code. Because post can be associated to multiple categories, so you need to check the post is already obtained.

Upvotes: 1

Related Questions