skip to Main Content

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

3

Answers


  1. as per my comments above. the code example I can give you is as follows

    for($i = 0; $i <= count($categories); $i++) {
        /* 
        Pagination purposes this is how you can format data to an object 
        base.
        */
        if($i % 3 = 0) {
           // add to an array
        }
    }
    
    for ($i = 0; $i <= 3; $i++) {
    // echo categories HTML but $categories[$i] instead
    }
    

    though let it be known that this wont fully work as you would think etc… etc… I cant explain the modulus operator in depth as I cant think of an easy way without you trying to learn it so you can understand it well.

    this way you are only getting 3

    Login or Signup to reply.
  2. $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>';
    }
    
    Login or Signup to reply.
  3. $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;
     }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search