This post is explaining creating wordpress custom meta boxes/meta data in easy,secure & proper way.A post meta box is a draggable box shown on the post adding/editing page. Its purpose is to allow the user to enter information in addition to the main post content.
There are two types of meta boxes.
1-Meta data
Check this attachment to get an idea about the meta box.
Post metadata is data that’s saved in the wp_postmeta table in the database.
Following functions are using working with post meta data.
add_post_meta() – Add post metadata.
update_post_meta() – Update post metadata.
delete_post_meta() – Delete post metadata.
get_post_meta() – Retrieve post metadata.
2-Taxonomy terms
Check this attachment to get an idea about the Taxonomy in wordpress.
I’ll explain about creating a custom post types in next post.
Creating a custom post meta box
ok.Now I’m going to show you how to create custom meta box in wordpress.
Look at this diagram and you can understand what I’m going to do now.
1-Add meta boxes on the ‘add_meta_boxes’ hook.
Open your theme’s folder functions.php file and add the following codes at the end of that file.
wp-content/themes/yourthemefolder/functions.php
/* Add meta boxes on the 'add_meta_boxes' hook. */ add_action( 'add_meta_boxes', 'my_portfolio_url' ); function my_portfolio_url() { add_meta_box( 'my_portfolio_url', // id, used as the html id att __( 'Add Portfolio URL' ), // meta box title 'my_portfolio_tasks', // callback function, spits out the content 'portfolio', // post type or page. This adds to posts only 'side', // context, where on the screen 'low' // priority, where should this go in the context ); }
2-Display the meta value
// display the meta value function my_portfolio_tasks( $post ) { global $wpdb; // get meta box data value $value = get_post_meta($post->ID, 'my_portfolio_url', true); // display the title echo ''; // display the text box to enter the value echo ''; echo ''; }
3-Save post meta on the ‘save_post’ hook
/* Save post meta on the 'save_post' hook. */ add_action( 'save_post', 'my_save_metadata'); function my_save_metadata($postid){ // check for AUTOSAVE if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false; // check the current user has permission to edit/create posts if ( !current_user_can( 'edit_page', $postid ) ) return false; if( empty($postid) ) return false; // check for empty value if ( is_null($_REQUEST["my_portfolio_url"]) ) { // delete value delete_post_meta($postid, 'sh_portfolio_url'); } else { // update value update_post_meta($postid, 'my_portfolio_url', $_REQUEST['my_portfolio_url']); } }
That’s only you have to do. Now clear the browser cache and check the post edit/create page and you can see the custom meta data value there.
I’ll show how to create custom post type of wordpress in next post.