Function Web Design & Development [ Blog ] ? ...

来源:百度文库 编辑:神马文学网 时间:2024/07/08 05:27:02
Write Panels in WordPress

Use Custom Write options to easily add any unique data to your post

Everyone knows that WordPress is one of the most, if not the most, popular blogging systems on the internet today. With its out of the box features, plugins, and great theming community, its no wonder WordPress has been accepted as today’s standard. However, sometimes you just want to add a little more.

It seems the latest fad to hit the WordPress scene is adding thumbnails into a blog post. This is fairly easy to do with some knowledge of custom fields, but can be a little complicated if your client is new to WordPress, or blogging.

Luckily, WordPress has a solution for us. We are going to use a little something called add_meta_box.

Note: This tutorial requires both knowledge of WordPress, as well as PHP.

I shared a link in a comment that WordPress has a little tutorial for this on their site. However, it is a little incomplete, and leaves a little to be desired. So, let’s get started making our own!

Examples of Usage

To see how you can use custom write panels take a look at these couple of examples, or click the image below.

functions.php

Please excuse the indention of the code. The WordPress plugin does not like my tabs.

All of the code we are about to add will be put in functions.php. This file is included automatically in the Theme, so anything we put in here can be used throughout the theme.

To make this expandable for the future, we are going to declare all of our information in an array. This way, we can add some information to the array, and it will be automatically added to our Admin Panel.

Information Array

view plaincopy to clipboardprint
  1.   
  2. /*  
  3. Plugin Name: Custom Write Panel  
  4. Plugin URI: http://wefunction.com/2008/10/tutorial-create-custom-write-panels-in-wordpress  
  5. Description: Allows custom fields to be added to the WordPress Post Page  
  6. Version: 1.0  
  7. Author: Spencer  
  8. Author URI: http://wefunction.com  
  9. /* ----------------------------------------------*/  
  10.   
  11. $new_meta_boxes =   
  12. array(   
  13.   
  14. );  

Inside of that array, we are going to add more arrays which will hold the information of the new meta box.

view plaincopy to clipboardprint
  1.   
  2. $new_meta_boxes =   
  3. array(   
  4. "image" => array(   
  5. "name" => "image",   
  6. "std" => "",   
  7. "title" => "Image",   
  8. "description" => "Using the \"Add an Image\" button, upload an image and paste the URL here.")   
  9. );  

The array is pretty self explanatory. The first value is the name of field, after that would be a standard value (in this case, it is blank, but this would be useful to store default information), and then the Title of the meta_box, ending with the description.

There are 3 functions that will be the backbone here. Let’s go ahead and declare those now:

view plaincopy to clipboardprint
  1.   
  2. function new_meta_boxes() {   
  3.   
  4. }   
  5.   
  6. function create_meta_box() {   
  7.   
  8. }   
  9.   
  10. function save_postdata( $post_id ) {   
  11.   
  12. }  

Creating the Fields

Lets work on function new_meta_boxes().

This is the function where we are going to build the actual HTML inputs. We first need declare a few variables as global. We will then be able to access them inside the function. We need to be able to access the $post variable, as well as $new_meta_boxes (our array.)

view plaincopy to clipboardprint
  1.   
  2. function new_meta_boxes() {   
  3. global $post, $new_meta_boxes;   
  4. }  

Because all of our information is in an array, we need to loop through it all, and create an input box for each one:

view plaincopy to clipboardprint
  1.   
  2. function new_meta_boxes() {   
  3. global $post, $new_meta_boxes;   
  4.   
  5. foreach($new_meta_boxes as $meta_box) {   
  6.   
  7. }  

Next we need to figure out a default value for the inputs. We can do this by checking the get_post_meta WordPress function.

view plaincopy to clipboardprint
  1.   
  2. function new_meta_boxes() {   
  3. global $post, $new_meta_boxes;   
  4.   
  5. foreach($new_meta_boxes as $meta_box) {   
  6. $meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);   
  7.   
  8. if($meta_box_value == "")   
  9. $meta_box_value = $meta_box['std'];   
  10. }  

This is some pretty simple PHP. We define $meta_box_value, and set it equal to get_post_meta. Next, we check to see if our variable == "" (equals nothing) meaning no data has been previously entered. If nothing has been entered, we set the $meta_box_value equal to the std value we defined in the array

Time to start building the inputs. First off, we are going to create a hidden field that we will use to verify the data later on.

view plaincopy to clipboardprint
  1.   
  2. echo'';  

Now we can echo the title of our Custom Input:

view plaincopy to clipboardprint
  1.   
  2. echo'

    '.$meta_box['title'].'

    ';  

Next our actual input box. This gets the value of $meta_box_value we worked out earlier.

view plaincopy to clipboardprint
  1.   
  2. echo'';  

Finally, just add our little description we defined in the array

view plaincopy to clipboardprint
  1.   
  2. echo'

    '.$meta_box['description'].'

    ';  

(All of that is still in our function new_meta_boxes() function.)

Make it Meta!

Our next function, function create_meta_box(), will actually create each of the meta boxes. We are going to be using WordPress’s add_meta_box

view plaincopy to clipboardprint
  1.   
  2. function create_meta_box() {   
  3. if ( function_exists('add_meta_box') ) {   
  4. add_meta_box( 'new-meta-boxes', 'Custom Post Settings', 'new_meta_boxes', 'post', 'normal', 'high' );   
  5. }   
  6. }  

if ( function_exists('add_meta_box') ) { is important because this function did not exist in versions of WordPress before version 2.5. You need to on at least version 2.5 before this will work.

From WordPress.org, the function works like this:

view plaincopy to clipboardprint
  1.   

callback is the most important. That is calling our function (new_meta_boxes). context decides whether or not this field should display on the “Write > Post” page, or the “Write > Page” page. You can read more about the parameters on the WordPress site

Saving the Data

Now here’s the important part, and the part where WordPress.org is pretty vague. This function will save our data.

view plaincopy to clipboardprint
  1.   
  2. function save_postdata( $post_id ) {   
  3. global $post, $new_meta_boxes;   
  4.   
  5. foreach($new_meta_boxes as $meta_box) {   
  6.   
  7. }   
  8. }  

This is our function, and we’ve started off with including a few variables. Again, we need to include $post so we have the ID of the WordPress post. Also, we have to include the $new_meta_box array, as we will loop through it again.

This next bit (inside of the foreach loop), will verify that the data we are receiving is genuine.

view plaincopy to clipboardprint
  1.   
  2. // Verify   
  3. if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {   
  4. return $post_id;   
  5. }   
  6.   
  7. if ( 'page' == $_POST['post_type'] ) {   
  8. if ( !current_user_can( 'edit_page', $post_id ))   
  9. return $post_id;   
  10. } else {   
  11. if ( !current_user_can( 'edit_post', $post_id ))   
  12. return $post_id;   
  13. }  

No we are going to define a variable that will get the data out of our fields.

view plaincopy to clipboardprint
  1.   
  2. $data = $_POST[$meta_box['name'].'_value'];  

It gets the $_POST data from our fields we created in the previous functions.

Now the last thing to do is to decide what to do with the new data. To keep WordPress from creating a new database entry each time, a few checks need to be made. First, we try and get any information with the same key and post id. If it returns empty, we know this custom field has not been added before. So, lets add it.

view plaincopy to clipboardprint
  1.   
  2. if(get_post_meta($post_id, $meta_box['name'].'_value') == "")   
  3. add_post_meta($post_id, $meta_box['name'].'_value', $data, true);  

Next, we check to see if the new data in the field is different from any old data. If it is, we simply update the field.

view plaincopy to clipboardprint
  1.   
  2. elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))   
  3. update_post_meta($post_id, $meta_box['name'].'_value', $data);  

The last thing to do is delete one, if the field is left empty. This will keep our database free of any blank entries.

view plaincopy to clipboardprint
  1.   
  2. elseif($data == "")   
  3. delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));  

Now, to actually make things work, we need to “hook” WordPress. We can do this by using add_action. This simply adds our functions to a specific area of WordPress. In our case, we need to hook the admin_menu, as well as when the post is saved, save_post.

view plaincopy to clipboardprint
  1.   
  2. add_action('admin_menu', 'create_meta_box');   
  3. add_action('save_post', 'save_postdata');  

Our Final Code

view plaincopy to clipboardprint
  1.   
  2. /*  
  3. Plugin Name: Custom Write Panel  
  4. Plugin URI: http://wefunction.com/2008/10/tutorial-create-custom-write-panels-in-wordpress  
  5. Description: Allows custom fields to be added to the WordPress Post Page  
  6. Version: 1.0  
  7. Author: Spencer  
  8. Author URI: http://wefunction.com  
  9. /* ----------------------------------------------*/  
  10.   
  11. $new_meta_boxes =   
  12. array(   
  13. "image" => array(   
  14. "name" => "image",   
  15. "std" => "",   
  16. "title" => "Image",   
  17. "description" => "Using the \"Add an Image\" button, upload an image and paste the URL here.")   
  18. );  
view plaincopy to clipboardprint
  1.   
  2. function new_meta_boxes() {   
  3. global $post, $new_meta_boxes;   
  4.   
  5. foreach($new_meta_boxes as $meta_box) {   
  6. $meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);   
  7.   
  8. if($meta_box_value == "")   
  9. $meta_box_value = $meta_box['std'];   
  10.   
  11. echo'';   
  12.   
  13. echo'

    '.$meta_box['title'].'

    ';   
  14.   
  15. echo'';   
  16.   
  17. echo'

    '.$meta_box['description'].'

    ';   
  18. }   
  19. }  
view plaincopy to clipboardprint
  1.   
  2. function create_meta_box() {   
  3. global $theme_name;   
  4. if ( function_exists('add_meta_box') ) {   
  5. add_meta_box( 'new-meta-boxes', 'Brazen Post Settings', 'new_meta_boxes', 'post', 'normal', 'high' );   
  6. }   
  7. }  
view plaincopy to clipboardprint
  1.   
  2. function save_postdata( $post_id ) {   
  3. global $post, $new_meta_boxes;   
  4.   
  5. foreach($new_meta_boxes as $meta_box) {   
  6. // Verify   
  7. if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {   
  8. return $post_id;   
  9. }   
  10.   
  11. if ( 'page' == $_POST['post_type'] ) {   
  12. if ( !current_user_can( 'edit_page', $post_id ))   
  13. return $post_id;   
  14. } else {   
  15. if ( !current_user_can( 'edit_post', $post_id ))   
  16. return $post_id;   
  17. }   
  18.   
  19. $data = $_POST[$meta_box['name'].'_value'];   
  20.   
  21. if(get_post_meta($post_id, $meta_box['name'].'_value') == "")   
  22. add_post_meta($post_id, $meta_box['name'].'_value', $data, true);   
  23. elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))   
  24. update_post_meta($post_id, $meta_box['name'].'_value', $data);   
  25. elseif($data == "")   
  26. delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));   
  27. }   
  28. }  
view plaincopy to clipboardprint
  1.   
  2. add_action('admin_menu', 'create_meta_box');   
  3. add_action('save_post', 'save_postdata');  

Implementation

Now I bet you are wondering “now how the heck do I get information?!” Well, it’s quite simple really. You do it the same way you would for a normal custom field. We’ve been using the function already in the tutorial, get_post_meta().

So, just open up one of your theme files where you want the custom data to appear. First, let’s check to see if there is anything entered for this post. Because if there isn’t, we shouldn’t show anything (in this case, it would result in a broken image.)

view plaincopy to clipboardprint
  1.   
  2. if(get_post_meta($post->ID, "image_value", $single = true) != "") :   
  3. ?>  

Now the actual image:

view plaincopy to clipboardprint
  1.   
  2.  src=" echo get_post_meta($post->ID, "image_value", $single = true); ?>" alt="" />  

And to end our if statement:

view plaincopy to clipboardprint
  1.   
  2. endif;   
  3. ?>  

Conclusion

As you can see, customizing WordPress is not an easy task. However, it pays off in the long run. By streamlining the User-Interface of adding custom data, you can help make your life, as well as your clients life a whole lot easier.

If you have any questions about the code above, or the tutorial in general, please do not hesitate to leave a comment below. I will do my best to help answer any questions that may arise.

Written by Spencer on October 20, 2008