Make WordPress Core

Opened 10 years ago

Closed 10 years ago

#30058 closed enhancement (duplicate)

Defined meta fields with expected data types for post type objects

Reported by: ajf-'s profile ajf- Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.1
Component: Posts, Post Types Keywords:
Focuses: Cc:

Description

There is currently no way of programmatically knowing which meta fields the theme or plugin author is adding to custom post types. Custom fields and meta boxes have their API, but the implementation details are left to the author, and there's no way of querying what fields a post type expects, which of them are required, and what data type each of them uses.

For example, if a plugin or theme author registers a post type for weather forecast: which has a temperature post meta key and a meta box that allows to edit that value.

register_post_type('weather_forecast'); 

// Add a meta box for 'temperature'
add_action( 'add_meta_boxes', function() { /* ... */ });

// On save post, save the meta data
add_action( 'save_post', function() { /* ... */ });

A use case for this is in the context of testing and automatic post generators for creating sample data. If the post meta model was defined in advance (in register_post_type, for example), plugins and theme authors would be able to know in advance what fields that post type expects.

Here is an example of this in the register_post_type function:

$args = array(
    'meta' => array(
        'temperature' => array(
              'data_type' => 'INT', // Could also be 'string', or even strings like 'price'. 
              'required' => true
        );
    );
);

In the context of testing or automatic sample data generation, one could then do something of the sorts of:

$available_post_types = get_post_types(array(
    'public' => true
), 'objects');

foreach ($available_post_types as $post_type) {
    $generated_id = wp_insert_post(array(/* .. */));
    foreach ($post_type->meta as $expected_meta_key => $expected_meta_value) {
        $generated_meta_value = generate_random_value_for($expected_meta_value); // fictitious function
        add_post_meta($generated_id, $expected_meta_key, $generated_meta_value);
    }
}

Change History (1)

#1 @nacin
10 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to duplicate
  • Status changed from new to closed

Yep! This is something the metadata working group have been considering, and I've mentioned this as well in some talks on metadata I gave over the last few months. This is a duplicate of the efforts arising out of #18179.

Note: See TracTickets for help on using tickets.