当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Get random category name from categories that are included in array, WordPress

问题描述:

I am trying to get a random category name. This random category has to come from a number of categories that are in an array.

I have tried the code below, but when I do it like this I will only get the category name (and id) of the first category that is in the included array (5).

How do I get the other ones to play along as well?

<?php

$args = array('hide_empty' => 1, 'include' => 5,14,15,19,20,25,27,28,29,31,33,141);

$categories = get_categories ($args);

if(!empty($categories)) :

$random_category = $categories[rand(0, (count($categories)-1))];

echo $random_category->slug . ", " . $random_category->term_id;

endif;

?>

网友答案:

The output shouldn't be an array but a string. The following code will work.

<?php 
$categories = get_categories('include=5,14,15,19,20,25,27,28,29,31,33,141&hide_empty=1');
if(!empty($categories)) {
    $random_category = $categories[rand(0, (count($categories)-1))];
    echo $random_category->slug . ", " . $random_category->term_id; 
} 
?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: