Come limitare il numero di termini (i termini funzionano come categorie)

10 set 2013, 21:32:22
Visualizzazioni: 16.4K
Voti: 6

Ciao, ho creato una tassonomia in un custom post type che funziona come categoria.

Poi ho creato dei termini che funzionano come categorie.

Ho creato un widget che mostra tutti i termini della tassonomia. Tutto funziona perfettamente.

Ma non riesco a capire come limitare il numero di termini da visualizzare.

Ho creato un input nel mio widget. Quindi se inserisco un numero, voglio che il widget limiti la visualizzazione solo a quel numero di termini.

Grazie per l'aiuto!

Il codice per mostrare tutti i termini è:

$terms = get_terms('new_category');
echo '<ul>';
foreach ($terms as $term) {
    $term_link = get_term_link( $term, 'new_category' );
    echo '<li><a href="' . $term_link . '"><div>' . $term->name . '</div></a></li>';

}
echo '</ul>';
1
Commenti

Hai letto la documentazione per get_terms?

Milo Milo
10 set 2013 21:37:17
Tutte le risposte alla domanda 3
0
number 
    (intero) Il numero massimo di termini da restituire. Il valore predefinito è restituirli tutti.

http://codex.wordpress.org/Function_Reference/get_terms

Quindi...

$terms = get_terms('new_category',array('number' => 5));

Ma c'è una buona probabilità che alcuni dei tuoi termini non vengano mai mostrati. Otterrai i primi cinque o gli ultimi cinque (nell'esempio) a seconda dell'ordinamento. Potresti voler usare invece qualcosa del genere:

$terms = get_terms('category');
if (!is_wp_error($terms)) {
  $pick = ($pick <= count($terms)) ?: count($terms);
  $rand_terms = array_rand($terms, $pick);
  echo '<ul>';
  foreach ($rand_terms as $key => $term) {
    $term =  $terms[$term];
    $term_link = get_term_link( $term );
    var_dump($term_link);
    if (!is_wp_error($term_link)) {
      echo '<li><a href="' . $term_link . '"><div>' . $term->name . '</div></a></li>';
    }
  }
  echo '</ul>';
}
10 set 2013 21:59:20
0
// Ottieni i primi 4 termini della tassonomia 'new_category'
$terms = get_terms('new_category', array('number' => 4));
// Inizia la lista non ordinata
echo '<ul>';
// Cicla attraverso ogni termine
foreach ($terms as $term) {
    // Ottieni il link al termine
    $term_link = get_term_link($term, 'new_category');
    // Stampa ogni termine come elemento di lista con link
    echo '<li><a href="' . $term_link . '"><div>' . $term->name . '</div></a></li>';
}
// Chiudi la lista non ordinata
echo '</ul>';
8 giu 2018 14:57:47
0

modifica il valore numerico come richiesto

$terms = get_terms('new_category', 'number=10');
echo '<ul>';
foreach ($terms as $term) {
    $term_link = get_term_link( $term, 'new_category' );
    echo '<li><a href="' . $term_link . '"><div>' . $term->name . '</div></a></li>';

}
echo '</ul>';
10 set 2013 21:51:14