Get Archive URL In Array Format With wp_get_archives And Regex

Imran Sayed
1 min readDec 1, 2021

In this blog, we will learn how to extract just the monthly archive URL/path , instead of markup.

function get_monthly_archive_array() {
$years = [];
$years_args = [
'type' => 'monthly',
'format' => 'custom',
'before' => '',
'after' => '|',
'echo' => false,
'post_type' => 'post',
// 'order' => 'ASC',
];

// Get Years
$years_content = wp_get_archives( $years_args );

if ( ! empty( $years_content ) ) {
$years_arr = explode( '|', $years_content );

// Remove empty whitespace item from array.
$years_arr = array_filter( $years_arr, function ( $item ) {
return trim( $item ) !== '';
} );

foreach ( $years_arr as $year_item ) {

$year_row = trim( $year_item );
preg_match( '/href=["\']?([^"\'>]+)["\']>(.+)<\/a>/', $year_row, $year_vars );

if ( ! empty( $year_vars ) && is_array( $year_vars ) ) {
$year_url = ! empty( $year_vars[1] ) ? $year_vars[1] : ''; // Eg: http://demo.com/2021/11/
$parts = parse_url( $year_url );
$path = ! empty( $parts['path'] ) ? $parts['path'] : '';

$years[] = [
'name' => $year_vars[2], // Eg: November 2021
'value' => $path // Eg: /2021/11/ , so that we can prefix o suffix our own URL.
];
}
}
}

return $years;
}

Output

--

--

Imran Sayed

👤 Full Stack Developer at rtCamp, Speaker, Blogger, YouTuber, Wordpress, React, Node, Laravel Developer http://youtube.com/ImranSayedDev