4

I have a recruitment website on which I want to display a list of Job Location links. The job location has already been entered into a custom field for each post so I just want to display a list of links that when clicked will show posts with only that custom value entered, ie -

England Ireland USA etc..

Click a country link above and see all of the posts that have the country in question added as a custom field value??

1 Answer 1

3

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 ...

1

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.