How to get a random single category name in get_posts()?

How can I get a random category name one at a time?? The post may have multiple category instead of a single category. I just want to show a single category name in the post grid loop.

$home_blog_posts = get_posts(array(
    'posts_per_page'    =  3
));

Thanks.

Topic get-posts theme-development query Wordpress

Category Web


You can use wp_get_post_categories to get the categories from your posts. Then you can use array_rand to get one random category from that array.

Check out these links on how to use wp_get_post_categories and array_rand to suit your needs:

https://developer.wordpress.org/reference/functions/wp_get_post_categories/ https://www.php.net/manual/en/function.array-rand.php

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.