4

Hello i have created taxonomy in custom post type that act like category.

then i have created terms that acts like categories.

i have create widget that show all terms from taxonomy. all works great.

but i can"t understand how to limit the number of terms to show.

i have created input in my widget. so if i put some number i want the widget will limit to show only this number of terms.

thanks for help!

the code to show all terms is:

$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>';
  • Have you read the documentation for get_terms? – Milo Sep 10 '13 at 18:37
5
number 
    (integer) The maximum number of terms to return. Default is to return them all. 

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

So...

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

But there is a good chance that some of your terms will never show up. You will get the first five or the last five (in the example) depending on the sort order. You may want something like this instead:

$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>';
}
| improve this answer | |
1

change number value as required

$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>';
| improve this answer | |
1
$terms = get_terms('new_category', array('number' => 4));
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>';
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.