I'm using wp_get_archives but I cannot prepend any text inside the links. I want code like this:

<a href="archive link">[my custom prepend] 2020<a/>

But the 'before' option will prepend the passed string before the <a> tag.

Current code is the following:

$archives = wp_get_archives(array(
  'type' => 'yearly'
  ,'echo' => false
  ,'format' => 'custom'
  ,'before' => 'News'

So I really would like to get a list of only years and urls, without any markup, so I can build it by myself. Thus maybe without wp_get_archives().

Maybe the best thing would be have a simple array like:

   array('year' => 2020, 'url' => 'https://www.....')

How to?

2 Answers 2


I was going to suggest creating a regex to parse it but if you look at this comment on the Wordpress wp_get_archives() docs it looks like someone has gotten there before us.

  • I already read it but it's not what I was looking for. Thank you anyway. Commented May 16, 2020 at 15:38
  • Unless I've miss understood the question it gives you almost exactly what you've asked for. Text and URL without any markup. Just need to tweak $years_args so that it's yearly not monthly and doesn't filter the post type.
    – Bob
    Commented May 16, 2020 at 16:41

I maneged to do like this:

First, get simply the years:

// this is a multipurpose function I made, and it's quite self explanatory
function get_years($post_type, $order = "ASC", $exclude = array(), $future = true, $taxonomy = null, $term = null){
  global $wpdb;
  $type = ($post_type) ? $post_type : 'post';
  $status = ($future) ? " ('publish', 'future') " : " ('publish') ";
  $exclude = (!empty($exclude)) ? " AND YEAR(post_date) NOT IN (" . implode(',',$exclude) . ") " : "";

  return $wpdb->get_results($wpdb->prepare("
    SELECT YEAR(post_date) AS `y`, count(ID) as posts_count
    FROM $wpdb->posts p
      INNER JOIN $wpdb->term_relationships rel ON p.ID = rel.object_id
      INNER JOIN $wpdb->term_taxonomy tt ON tt.term_taxonomy_id = rel.term_taxonomy_id
      INNER JOIN $wpdb->terms t ON tt.term_id = t.term_id
      p.post_type = %s
      AND tt.taxonomy = %s
      AND t.slug = %s
      AND post_status IN " . $status . "
    GROUP BY y
    ORDER BY post_date " . $order,

Then, cicle through the years and build the permalinks:

get_year_link($year); // this is wp. 

It works for posts, otherwise one could build the likes in a more 'manual' way:

home_url(user_trailingslashit('write some path here' . $year));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.