Filter custom posts using auto populated dropdown selectors

I’ve created a custom post type named agent.

I have a page that lists all agents.

Read More

When I add an agent I have a whole series of custom meta boxes that can be filled out, region, specialty, language…

I’d like to add a series of dropdown boxes on the front end that will populate with all the terms from each custom meta. For example a regions dropbox would populate with all the regions from all the agents. If I add a new agent in a new region, the dropbox will automatically pick that up.

Thanks for looking.

Related posts

Leave a Reply

1 comment

  1. If you’d try to do this, you’d end up with querying a maybe pretty big load of data, which should be avoided.

    Best would be to pre-collect the data in some global (array) $prefix_meta_box_values and use this later for front-end output.

    You could also populate some array on save_post hook. Simply grap the values with get_post_meta( $post_id, 'key', 'value' ) inside a function on your post edit screen in admin UI and add it to some db-field with update_option('agents_data'). This would allow you to call get_option('agents_data'); in the front end and populate your select boxes.

    Update:

    // The updata agents option could look like this, asuming that you already added 
    // some data with an add_option call somewhere. Else you could just grap the old
    // data, merge it with the new and update the post meta field.
    // This was fastly written out of my head, so don't expect it to work without any fixing.
    function my_agents_data() 
    {
      $new_agents_data = get_post_meta( $GLOBALS[$post]->ID, 'key', 'value' );
      $old_agents_data = get_option( 'agents_data' );
      $resulting_agents_data = array_merge( $old_agents_data, $new_agents_data );
      update_option( 'agents_data', $resulting_agents_data );
    }
    add_action( 'save_post', 'my_agents_data' );
    

    This would allow you to get the option data from get_option('agents_data') option field in wp options table. Point with this is, that you then should avoid that the meta data get’s into the post meta table.