'Set up a number of categories to display on a page

I am basically looking for a way to display only 3 categories on my template page. I used a foreach loop to display all the categories on my pages

$categories = get_categories();
foreach($categories as $category) {
   echo '<div class="col-md-4"><a href="' . 
    get_category_link($category->term_id) . '">' . $category->name 
  . '</a></div>';
}?>

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations



Solution 1:[1]

$page=$_GET['page_number']; 

$categories = get_categories();

$data=array_chunk($categories ,3);

$paginations=count($data); // use loop for paginations in html page

foreach($data[$page] as $category) {
   echo '<div class="col-md-4"><a href="' . 
    get_category_link($category->term_id) . '">' . $category->name 
  . '</a></div>';
}

Solution 2:[2]

$startCategory = 0;
for($i = $startCategory; $i <= count($categories); $i++) {
 echo '<div class="col-md-4"><a href="' .get_category_link($categories[$i]['term_id']) . '">' . $categories[$i]['name']. '</a></div>';
 $startCategory++;
 if($startCategory > (count($categories) -1)){
  break;
 }
//pass $startCategory to next page , next page
$startCategory  = $_POST["startCategory"]; // by using post method

$startCategory  = $_GET["startCategory"]; // by using get method
for($i = $startCategory; $i <= count($categories); $i++) {
echo '<div class="col-md-4"><a href="' . 
    get_category_link($categories[$i]['term_id']) . '">' . $categories[$i]['name']
  . '</a></div>';
$startCategory++;
 if($startCategory > (count($categories) -1)){
  break;
 }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 dvlpr.963