Skip to content

Instantly share code, notes, and snippets.

@BenBroide
Created January 4, 2021 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenBroide/29444cbd51180920cdb7783da5c6234a to your computer and use it in GitHub Desktop.
Save BenBroide/29444cbd51180920cdb7783da5c6234a to your computer and use it in GitHub Desktop.
<?php
function sgf_meta_fields() {
$fields_array = apply_filters( 'sgf_register_fields', [] );
foreach ( $fields_array as $field ) {
// Ensure post type exists and field name is valid
if ( ! $field['post_type'] || ! post_type_exists( $field['post_type'] ) || ! $field['meta_key'] || ! is_string( $field['meta_key'] ) ) {
return;
}
// Using Null Coalesce Operator to set defaults
register_post_meta( $field['post_type'], $field['meta_key'], [
'type' => $field['type'] ?? 'string',
'single' => $field['single'] ?? true,
'default' => $field['default'] ?? '',
'show_in_rest' => $field['show_in_rest'] ?? true,
'control' => $field['control'] ?? 'text'
] );
}
}
add_action( 'rest_api_init', 'sgf_meta_fields' , 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment