Search code examples
arrayswordpresscustom-post-typearchive

Create an array with all the links of the years' archive (of a custom post type)


I have a custom post type called "papers" and I need to create an array with all the archive links per year that exists. Something like:

array (
[0]=> 'http://www.example.com/2021/?post_type=papers'
[1]=> 'http://www.example.com/2019/?post_type=papers'// cause there's no post in 2020
[2]=> 'http://www.example.com/2017/?post_type=papers'
)

I've been told to use get_archives() but that just gives me a formated list, not an array I can use to feed another function. Or am I doing something wrong?


Solution

  • Try this:

      $links = wp_get_archives(array('echo'=>'0','format'=>'<link>'));
      $regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';
      preg_match_all($regex, $links, $matches);
      $array_links = $matches[0];
      print_r($array_links);