WordPress.org

Support

Support » Themes and Templates » custom fields and custom meta boxes

custom fields and custom meta boxes

  • Robert Simpson
    Participant

    @rsimpson

    Hi folks,

    I’m wondering if anyone can point me at a tutorial that’ll teach me how to take some custom fields that I have and create custom meta boxes for them.

    Right now I have some code that’s allowed me to create a form which loads below the visual editor but unfortunately it saves all of the info to an array within a single custom field, ordinarily this would be great but in this case I need to save all of the values into separate custom fields.

    The reason I have to do it this way is due to my custom post types and the custom meta boxes I’ve created for them. They’re all working great but I want there to be a few custom fields which both custom posts and standard ‘post’ posts have in common, my current setup doesn’t allow for this.

    Any help would be greatly appreciated 🙂

    Cheers,
    Rab

Viewing 13 replies - 1 through 13 (of 13 total)
  • Robert Simpson
    Participant

    @rsimpson

    *bump*

    I’m a little confused on what you’re asking, you want to add meta boxes to all of your pages/post types or just your custom ones? if you want custom fields that don’t neccesarily appear under the custom fields tab just do something like this:

    //Put all your arguments and details in the array.. Example:
    $meta_boxes = array(
           "background_image" => array(
    		"name" => "background_image",
    		"title" => "Page Background Image",
    		"type" => "text",
    		"description" => "A background image for the page.")
    );
    //Hook into the admin_menu
    add_action('admin_menu', 'create_meta_box');
    function create_meta_box() {
    	add_meta_box( 'meta-box-id', 'The Title', 'display_meta_box', 'post', 'normal', 'high' );
    }
    
    //Display the meta_boxes
    function display_meta_box($meta_boxes) {
    $data = get_post_meta($post->ID, $key, true);
    <div class="form_wrap">
    <?php foreach($meta_boxes as $meta_box) {
    <div class="form_field">
    <label for="<?php echo $meta_box['name']; ?>"><?php echo $meta_box['title']; ?></label>
    <input type="text" name="<?php echo $meta_box['name']; ?>" value="<?php echo htmlspecialchars( $data[$meta_box['name']] ); ?>" />
    <p><?php echo $meta_box[ 'description' ]; ?></p>
    </div>
    </div>
      }
    }
    
    //Function to save your fields
    add_action('save_post', 'save_meta_box');
    function save_meta_box( $post_id ) {
      global $post;
        foreach( $meta_boxes as $meta_box ) {
    		$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
    	}
      //Make sure the POST info came from WP..
       if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
    	return $post_id;
    
    	if ( !current_user_can( 'edit_post', $post_id ))
    	return $post_id;
    
    	update_post_meta( $post_id, $key, $data );
        }
    }

    Obviously this can be expanded upon to display the form however you’d like but thats the gist of what needs to be done for any custom meta box info you want to add..

    Robert Simpson
    Participant

    @rsimpson

    Hi tjsix,

    Thanks for your reply. Yeah really I’d like to have the custom meta boxes just on regular posts, I already know how to do it when declaring a custom post type, I just didn’t know how to go about doing it for regular posts.

    Is there a way I can have it load a different form (with different meta boxes) dependent on whether it’s a post or a page? Or am I stuck with the same form on both forms and pages?

    Cheers,
    Rab

    Yup, you just change the add_meta_box( ‘meta-box-id’, ‘The Title’, ‘display_meta_box’, ‘post’, ‘normal’, ‘high’ ); to page instead of post… (or add a second one) you could do two separate functions for displaying each differently, or just have them all display the same just display different info..

    For instance in most of my themes I have two arrays, usually $meta_boxes_page and $meta_boxes_post and I add an additional two functions from what I posted above, display_meta_box_page and display_meta_box_post, each are essentially the same and just pass the arrays to my display_meta_box() function, and they are both called from the add_meta_box() function..

    Robert Simpson
    Participant

    @rsimpson

    Hi tjsix,

    I’ve taken your code above and put it in it’s own file and included that file in functions.php. It returned an error when I went to post.php saying there was an extra } at the end so I’ve removed it.

    Here’s the code as it is now:

    <?php
    /**
    * This file handles the custom meta boxes found on posts (and pages once I've worked them into it).
    */
    
    // Put all your arguments and details in the array. Example:
    $meta_boxes = array(
    	"background_image" => array(
    		"name" => "background_image",
    		"title" => "Page Background Image",
    		"type" => "text",
    		"description" => "A background image for the page."
    	)
    );
    
    // Hook into the admin_menu
    add_action('admin_menu', 'create_meta_box');
    function create_meta_box() {
    	add_meta_box( 'meta-box-id', 'The Title', 'display_meta_box', 'post', 'normal', 'high' );
    }
    
    // Display the meta_boxes
    function display_meta_box($meta_boxes) {
    	$data = get_post_meta($post->ID, $key, true);
    	?><div class="form_wrap">
    		<?php foreach($meta_boxes as $meta_box) { ?>
    		<div class="form_field">
    			<label for="<?php echo $meta_box['name']; ?>"><?php echo $meta_box['title']; ?></label>
    			<input type="text" name="<?php echo $meta_box['name']; ?>" value="<?php echo htmlspecialchars( $data[$meta_box['name']] ); ?>" />
    			<p><?php echo $meta_box[ 'description' ]; ?></p>
    		</div>
    		<?php } ?>
    	</div>
    <?php }
    
    // Function to save your fields
    add_action('save_post', 'save_meta_box');
    function save_meta_box( $post_id ) {
    	global $post;
    	foreach( $meta_boxes as $meta_box ) {
    		$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
    	}
    
    	//Make sure the POST info came from WP.
    	if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) ) return $post_id;
    
    	if ( !current_user_can( 'edit_post', $post_id )) return $post_id;
    
    	update_post_meta( $post_id, $key, $data );
    }
    
    ?>

    It’s done something very strange when the page is displayed, have a look here: http://www.rsimpson.net/strange-meta-behaviour.gif

    Have you ever seen this before?

    Cheers,
    Rab

    It’s probably because the $key is not defined.. define the key at the top, you can set it to whatever you want and it’s usually the shortname for the theme.. so just set it to $key = mytheme; or whatever.. the key just needs to be a unique identifier..

    Also, in the create_meta_box and display_meta_box functions call the key in the global scope with global $key;

    Robert Simpson
    Participant

    @rsimpson

    Thanks for your efforts tjsix but I just couldn’t work it out.

    I followed this tutorial (http://webdesignfan.com/custom-write-panels-in-wordpress/) which I had working up until I tried to get it working with both ‘post’ and ‘page’ post types.

    Everything works up until I try to save the post. It seems $meta_box[‘fields’] isn’t being submitted and I can’t work out why. I haven’t touched the code within the function at the bottom. Here’s my code: http://pastebin.com/q1e7iKkN

    Does anyone have any ideas where I’m messing up?

    Cheers,
    Rab

    Is it giving you any errors or just not saving the data you put in?

    Robert Simpson
    Participant

    @rsimpson

    Yup it comes back with this:

    Warning: Invalid argument supplied for foreach() in /path/wp-content/themes/theme/functions/custom-meta-boxes.php on line 179
    
    Warning: Invalid argument supplied for foreach() in /path/wp-content/themes/theme/functions/custom-meta-boxes.php on line 179
    
    Warning: Cannot modify header information - headers already sent by (output started at /path/wp-content/themes/theme/functions/custom-meta-boxes.php:179) in /path/wp-includes/pluggable.php on line 897

    If I var_dump the array (you can see it commented out in the code) it returns NULL.

    Cheers,
    Rab

    You should consider this “framework” for metaboxes. Makes it so much easier.

    Thanks for that link MrVictor!

    Robert Simpson
    Participant

    @rsimpson

    I’m using GD Custom Posts and Taxonomies Tools now which comes with everything I need as far as meta boxes are concerned, even including rich text meta boxes.

    The only down side is that it’s not a free plugin but at this point I really don’t care because it’s totally worth it and the developer does an outstanding job with it. I have to give credit where it’s due and in this case it most certainly is!

    ajuliano
    Participant

    @ajuliano

    @dcg627

    The framework MrVictor is talking about has become a plugin, still light weight with no UI.

    http://wordpress.org/extend/plugins/meta-box/

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘custom fields and custom meta boxes’ is closed to new replies.