skip to Main Content

I use this code to get monthly articles archive

And I have a problem when I use get_the_permalink(); I don’t get a link to the articles of the month

$all_posts = get_posts(array(
    'posts_per_page' => - 1, 
    'post_type' => 'news'

));

$ordered_posts = array();

foreach ($all_posts as $single)
{
    $year = mysql2date('Y', $single->post_date);
    $month = mysql2date('F', $single->post_date);
    $ordered_posts[$year][$month][] = $single;
}
foreach ($ordered_posts as $year => $months)
{ ?>

<?php foreach ($months as $month => $posts)
    { ?>    
    <a href="<?php get_the_permalink(); ?>">
                <div class="arch-year-month">                
                <div class="arch-month"><?php echo $month ?></div><div class="arch-year">  <?php echo $year ?></div></div></a>                                              
      <?php
    }
?>
   <?php
}
?>

2

Answers


  1. Chosen as BEST ANSWER

    I found this solution,

    $all_posts = get_posts(array(
      'posts_per_page' => -1, 
      'post_type' => 'news'
    
    ));
    
    
    
    $myMonth = array();
    foreach ($all_posts as $single) {
     $month = mysql2date('F', $single->post_date);
     $month_number = mysql2date('m', $single->post_date);
     $myMonth[$month] = $month_number;
    }
    
    
    
    $ordered_posts = array();
    foreach ($all_posts as $single) {
      $year  = mysql2date('Y', $single->post_date);
      $month = mysql2date('F', $single->post_date);
      $month_number = mysql2date('m', $single->post_date);
    
      $ordered_posts[$year][$month][] = $single;
      
    }
    
    foreach ($ordered_posts as $year => $months) {
    foreach ($months as $month => $posts ) { 
    ?>
    
    <?php 
    
      ?>
        <a href="/news-date/<?php echo $year ?>/<?php echo $myMonth[$month]; ?>">
                    <div class="arch-year-month">
                     
                    <div class="arch-month"><?php echo $month ?></div><div class="arch-year">  <?php echo $year ?>
                    </div>
                    </div>
                    </a>
                    
                    
                    
          <?php
          } 
        
    } 
    ?>
    

  2. replace the code with <a href="<?php echo get_month_link($year, date('m',strtotime($month))); ?>this code, hope it will work. It is the specific month’s link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search