简体   繁体   中英

Displaying random Taxonomy terms in Wordpress

I am trying to display random taxonomy terms in wordpress ordered alphabetically according to its title.

I am using the following code which does display the categories randomly but is not displayed alphabetically.

<?php
//display random sorted list of terms in a given taxonomy
$counter = 0;
$max = 5; //number of categories to display
$taxonomy = 'cp_recipe_category';
$terms = get_terms($taxonomy, 'orderby=name&order= ASC&hide_empty=0');
shuffle ($terms);
//echo 'shuffled';
if ($terms) {
foreach($terms as $term) {
    $counter++;
    if ($counter <= $max) {
    echo '<p><a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a></p> ';
    }
}
}
?>

Since get_terms orders by name by default

get_terms('taxonomy='.$taxonomy.'&hide_empty=0');

should be enough.

To get random terms in alphabetical order

<?php

$max = 5; //number of categories to display
$taxonomy = 'cp_recipe_category';
$terms = get_terms('taxonomy='.$taxonomy.'&orderby=name&order=ASC&hide_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 '<p><a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a></p> ';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM