Add Custom Field Meta Box (2 posts)

  1. alanchrishughes
    Posted 4 years ago #

    I had been searching quite a while for a tutorial that would actually work and I finally found one the other day


    I broke down that code to the very basics to simply return an address line with a post which has been working.

    add_action('admin_menu', 'RestaurantGuideAddressLineOne');
    add_action('save_post', 'save_RestaurantGuideAddressLineOne');
    function RestaurantGuideAddressLineOne() { add_meta_box('RestaurantGuideAddressLineOne', 'Address Line One', 'RestaurantGuideAddressLineOne_input_function', 'restaurantguide', 'normal', 'high');}
    function RestaurantGuideAddressLineOne_input_function() {
    global $post;
    echo '<input type="text" name="RestaurantGuideAddressLineOne_input" id="RestaurantGuideAddressLineOne_input" style="width:100%;" value="'.get_post_meta($post->ID,'_RestaurantGuideAddressLineOne',true).'" />';
    function save_RestaurantGuideAddressLineOne($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
    $RestaurantGuideAddressLineOne = $_POST['RestaurantGuideAddressLineOne_input'];
    update_post_meta($post_id, '_RestaurantGuideAddressLineOne', $RestaurantGuideAddressLineOne);

    The problem is though, for whatever reason this code requires you start the name of your custom field with an _underscore. The problem with that is, I already have a very large chunk of a site setup with regular names with no underscores. I would prefer to not have to go through re-entering 100+ restaurant listings just to add and underscore.

    Is there a way around this where I could use the code above but without the underscore?


  2. alanchrishughes
    Posted 4 years ago #

    I discovered the problem, I thought the underscore between save and the post type name was just part of the coding, not the name, but that was part of the name. So I just had to take that out and change it from

    add_action('save_post', 'save_RestaurantGuideAddressLineOne');


    add_action('save_post', 'saveRestaurantGuideAddressLineOne');

    which seems kind of funny being right next to each other, but apparently that is how it works. I hope this helps somebody else because I know it took me a long time to find this and it seems like something that would be a very basic and widely used feature.

Topic Closed

This topic has been closed to new replies.

About this Topic