Display a list of random terms from custom taxonomy with shortcode

I try to output a list of terms from my custom taxonomy. I am almost sure I was using this code snippet before, but somehow WP throws errors:

  • shuffle() expects parameter 1 to be array
  • array_slice() expects parameter 1 to be array
  • usort() expects parameter 1 to be array, null given
/* Show Custom Taxonomy Terms */

function these_rand_tax1() {
$max = 8; //number of categories to display
$taxonomy = 'baumaschinen_cat';
$terms = get_terms('taxonomy='.$taxonomy.'orderby=nameorder=ASChide_empty=0');


// Random order
shuffle($terms);


// Get first $max items
$terms = array_slice($terms, 0, $max);


// Sort by name
usort($terms, function($a, $b){
  return strcasecmp($a-name, $b-name);
});


// Echo random terms sorted alphabetically
if ($terms) {
  foreach($terms as $term) {
    echo 'pa href=' .get_term_link( $term, $taxonomy ) . ' title=' .  sprintf( __( View all posts in %s ), $term-name ) . ' ' . '' . $term-name.'/a/p ';
  }
}
}


add_shortcode('random_taxonomies','these_rand_tax1');
add_filter('widget_text', 'do_shortcode');

How can I achieve to get a random list from my custom taxonomy terms?

Topic advanced-taxonomy-queries shortcode functions custom-taxonomy categories Wordpress

Category Web


Try this code:

function these_rand_tax1()
{
    $max = 8; //number of categories to display
    $taxonomy = 'baumaschinen_cat';
    $terms = get_terms('taxonomy=' . $taxonomy . '&orderby=name&order=ASC&hide_empty=0');
    $terms = (array)$terms;

    // Random order
    shuffle($terms);


    // Get first $max items
    $terms = array_slice($terms, 0, $max);


    // Sort by name
    usort($terms, function ($a, $b)
    {
        return strcasecmp($a->name, $b->name);
    });


    // Echo random terms sorted alphabetically
    if ($terms)
    {
        foreach ($terms as $term)
        {
            echo '<p><a href="' . get_term_link($term['slug'], $taxonomy) . '" title="' .  sprintf(__(" View all posts in %s"), $term['name']) . '" ' . '>' . $term['name'] . '</a></p> ';
        }
    }
}

About

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