The get_month_link() WordPress PHP function retrieves the permalink for the month archives with year.
Usage
get_month_link($year, $month);
Parameters
- $year (int|false) – Integer of the year, or false for the current year.
- $month (int|false) – Integer of the month, or false for the current month.
More information
See WordPress Developer Resources: get_month_link
Examples
Displaying the current month’s archive link
// Display the link to the current month's archive echo '<a href="' . get_month_link(false, false) . '">All posts this month</a>';
Assigning a specific month’s archive link to a variable
// Assign the archive link for October 2004 to the variable $oct_04 $oct_04 = get_month_link(2004, 10);
Displaying the archive link for a specific post’s month
// Within The Loop, assign the year and month of the current post $archive_year = get_the_time('Y'); $archive_month = get_the_time('m'); // Display the link to the archive for the post's month and year echo '<a href="' . get_month_link($archive_year, $archive_month) . '">Archive for ' . get_the_time('F Y') . '</a>';
Displaying the archive link for the previous month
// Get the current month and year $current_year = date('Y'); $current_month = date('m'); // Calculate the previous month and year $previous_month = $current_month - 1; $previous_year = $current_year; if ($previous_month == 0) { $previous_month = 12; $previous_year--; } // Display the link to the previous month's archive echo '<a href="' . get_month_link($previous_year, $previous_month) . '">Posts from the previous month</a>';
Displaying a list of archive links for the past six months
// Get the current month and year $current_year = date('Y'); $current_month = date('m'); // Loop through the past six months for ($i = 1; $i <= 6; $i++) { // Calculate the month and year $month = $current_month - $i; $year = $current_year; while ($month <= 0) { $month += 12; $year--; } // Display the link to the archive for the month and year echo '<a href="' . get_month_link($year, $month) . '">Archive for ' . date('F Y', strtotime("$year-$month-01")) . '</a><br>'; }