njinok
njinok

Reputation: 65

Changing Wordpress function

I'm using a Wordpress function to enter the word 'and' before the last term in calling a term list, like this:

function TermList($taxonomy = 'markup') {
    global $post;
    $term_list = '';
    $terms = get_the_terms($post->ID, $taxonomy);
    $n = 1;
    if ($terms) {
        foreach($terms as $term) {
            if ($n < count($terms)) {
                $term_list .= $term->name . ', ';
            } else {
                $term_list = rtrim($term_list, ', ') .  ' and ' . $term->name;
            }
            ++$n;
        }
    }

    $term_list = rtrim($term_list, ', ');

    return $term_list;
}

I want to change this function so it only displays 5 terms and chooses those 5 terms randomly from all available terms. I don't know where to start. Who can point me in the right direction?

Upvotes: 0

Views: 31

Answers (1)

Marcello Perri
Marcello Perri

Reputation: 610

Using array_rand

You could use array_rand in php to select a random element from an array, here is the official documentation from php.net

and your code will be something like:

for($i=0 ; $i<5 ; $i++){
    $term_list .=  $terms [array_rand($terms )] . ', ';
}
$term_list = rtrim($term_list, ', ');

// replace the last comma with 'and'
$portion = strrchr($term_list , ',');
$term_list = str_replace($portion, (" and" . substr($portion, 1, -1)), $term_list );

Using shuffle and array_slice

Another solution to pick up random elements from an array could be using shuffle to randomly shuffle the elements of an array and then using array_slice to pick up certain elements.

Here is an example of code:

shuffle($terms );
print_r(array_slice($terms , 0, 3));

Upvotes: 1

Related Questions