Show links to archive pages based on custom field values

I would recommend using a custom taxonomy for this, not a custom field. You can sort and list archives based on a taxonomy far more easily than by custom fields.

However, if you want to list based on the custom field, you’re going to need to modify the arguments sent to query_posts() on your archive page to pass in the meta_key and meta_value you’re searching by.

To add your query variable:

add_action('init', 'add_custom_meta_url');
function add_custom_meta_url() {
    global $wp,$wp_rewrite;
    $wp->add_query_var('location');
    $wp_rewrite->add_rule('location/([^/]+)','index.php?location=$matches[1]','top');
    $wp_rewrite->flush_rules(false);  // This should really be done in a plugin activation
}

Then, your permalinks for the archive will become something along the lines of http://mycoollocationsite.com/location/england http://mycoollocationsite.com/location/ireland http://mycoollocationsite.com/location/usa … etc …

Next, you’ll need to add whatever value was passed in to your location to the actual query:

add_action('parse_query', 'apply_custom_meta_to_query');
function apply_custom_meta_to_query(&$query) {
    if (isset($query->query['location'])) {
        $query->query_vars['meta_key'] = 'location';
        $query->query_vars['meta_value'] = $query->query['location'];
        unset($query->query_vars['location']);            // You don't need this

    }
}

I’m assuming you’re storing your custom data in a field called location … so change that if I’m wrong.

But this will allow you to filter your archives based on a specific location. If you want to enable date-based archives with this as well that will require some additional rules in my first code block (right now, this would display a list of all posts with a location meta_key).

Still, I recommend using a custom taxonomy instead. It’s cleaner, more extensible, and requires less custom coding. This is also exactly the situation for which custom taxonomies were created … so please, don’t reinvent the wheel …

Leave a Comment