How can I add pre-defined options to the “add new” custom field dropdown?

enter image description here

Here’s two examples of automatically adding and showing new custom fields:

  1. WordPress: Adding Default Custom Fields on New Posts
  2. Auto create custom field

That’s close to what I want to do; my goal is to add pre-defined options to the “add new” custom filed dropdown, but not have them show as fields until the blogger adds them.

I’d like to know how to do this without using a plugin.

4

You cannot do that with pure PHP, because the fields are fetched from existing fields, and there is no hook. But you can use JavaScript, check if the post type supports custom fields and the field does not exist already – and insert it:

<?php # -*- coding: utf-8 -*-
/* Plugin Name: Extend custom fields */

add_action( 'admin_footer-post-new.php', 'wpse_98269_script' );
add_action( 'admin_footer-post.php', 'wpse_98269_script' );

function wpse_98269_script()
{
    if ( ! isset ( $GLOBALS['post'] ) )
        return;

    $post_type = get_post_type( $GLOBALS['post'] );

    if ( ! post_type_supports( $post_type, 'custom-fields' ) )
        return;
    ?>
<script>
    if ( jQuery( "[value="demo_data"]" ).length < 1 ) // avoid duplication
        jQuery( "#metakeyselect").append( "<option value="demo_data">demo_data</option>" );
</script>
    <?php
}

Leave a Reply

Your email address will not be published. Required fields are marked *