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

Time:09-30

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?

CodePudding user response:

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);

CodePudding user response:

Please try this -

function get_archive_post_ids(){
    if( is_archive() ){
        global $wp_query;
        $post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
    }
}
add_action( 'wp_enqueue_scripts', 'get_archive_post_ids' );
  • Related