{"id":528,"date":"2013-11-28T03:16:14","date_gmt":"2013-11-28T03:16:14","guid":{"rendered":"http:\/\/a1webdesignteam.com\/blog\/?p=528"},"modified":"2013-11-28T03:16:14","modified_gmt":"2013-11-28T03:16:14","slug":"how-to-add-meta-boxes-to-provide-extra-content-for-wordpress-posts","status":"publish","type":"post","link":"https:\/\/a1webdesignteam.com\/blog\/how-to-add-meta-boxes-to-provide-extra-content-for-wordpress-posts\/","title":{"rendered":"How to Add Meta Boxes to Provide Extra Content for WordPress Posts"},"content":{"rendered":"<p>I started a new blog several months back and I wanted to include extra boxes on the WordPress edit\/add post screen to provide extra \u201cbehind the scenes\u201d data.<\/p>\n<p>More specifically I started to learn more about how meta tags (HTML elements that aren\u2019t shown in the browser unless \u201cviewing source\u201d) can influence what is shown when a web page is shared to social networks like Facebook, Google+ and Twitter, and on search engines.<\/p>\n<p>Wanting to control each aspect of the sharing for each site, I decided to create the necessary fields to allow me to do that on a post-by-post basis.<\/p>\n<h3>Examples of Meta Tags and Open Graph Tags<\/h3>\n<p>There are elements in HTML called \u201copen graph tags\u201d and when used will be the first place specific web sites, like Facebook and Google+, will look to learn about the content (rather than guessing).<\/p>\n<p>A few examples of these tags include: og:title, og:image, and og:description. When included in between the \u201chead\u201d HTML tags of a web page, sites (Facebook for example) will use the values when the URL to the web page is shared.<\/p>\n<p>There are also Twitter-specific meta tags that can be added to create media rich Twitter cards when the URL is shared.<\/p>\n<p>Here\u2019s how the Facebook Open Graphs would look within the HTML code when viewing the behind the scenes (or source) code:<\/p>\n<pre>&lt;meta content=\"This is the Open Graph or Facebook specific title\" \/&gt;\r\n&lt;meta content=\"http:\/\/web-site-example.com\/images\/example-image.png\" \/&gt;\r\n&lt;meta name=\"description\" content=\"This is the Open Graph or Facebook specific description\" \/&gt;<\/pre>\n<p>So, what\u2019s the point? If you want to have the ability to a) explicitly tell Facebook what data to use when displaying your content so it doesn\u2019t guess which can be embarassing especially when it uses an ad image as the image, and b) have more control over your call to action, etc. when your content is shared throughout Facebook (or Twitter, etc. \u2013 whatever the case may be).<\/p>\n<h3>Creating the Boxes to Add the Extra Data Into WordPress Posts<\/h3>\n<p>Now, this post isn\u2019t about sharing content to Facebook or Google+, it\u2019s about adding the Meta boxes to posts to provide extra data, so I don\u2019t want to pigeon hole this idea for just the \u201csocial sharing\u201d concept.<\/p>\n<p>I just wanted to provide an example of one purpose that they could be used for. Meta boxes are the foundation of why many plugins are built, and they also exist for many themes. Really, they just provide a way to include extra data for posts (and pages in some cases). Custom post types are borne from them.<\/p>\n<p>In this example I will show you how to include one panel with one text box to add a value. Then I will explain how to retrieve that information within a template file. The code can be modified to include more than one text box (or other form element) to add to the functionality. It\u2019s easier to just start with one and you could work up from there.<\/p>\n<p>Here\u2019s the code which can be placed in the functions.php file to create a box beneath the post edit and add screens:<\/p>\n<pre>&lt;?php\r\nadd_action( 'add_meta_boxes', 'm_param_meta_box_add' );\r\nfunction m_param_meta_box_add() {\r\n    add_meta_box( 'm_param_post', 'Box Title', 'm_param_post_meta_box_cb', 'post', 'normal', 'high' );\r\n}\r\n\r\nfunction m_param_post_meta_box_cb( $post )\r\n{\r\n    $values = get_post_custom( $post-&gt;ID );\r\n    if ( isset( $values['m_meta_description'] ) ) {\r\n        $m_meta_description_text = esc_attr( $values['m_meta_description'][0] );\r\n    }\r\n    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );\r\n\r\n?&gt;\r\n&lt;table&gt;\r\n&lt;tr valign=\"top\"&gt;\r\n&lt;th scope=\"row\"&gt;&lt;label for=\"m_meta_description\"&gt;Meta Description (max 160)&lt;\/label&gt;&lt;\/th&gt;\r\n&lt;td&gt;&lt;textarea rows=\"5\" cols=\"100\" name=\"m_meta_description\"&gt;&lt;?php echo $m_meta_description_text; ?&gt;&lt;\/textarea&gt;&lt;\/td&gt;\r\n&lt;\/tr&gt;\r\n&lt;\/table&gt;\r\n\r\n&lt;?php\r\n} \/\/ close m_param_post_meta_box_cb function\r\n\r\nadd_action( 'save_post', 'cd_meta_box_save' );\r\nfunction cd_meta_box_save( $post_id )\r\n{\r\n    \/\/ Bail if we're doing an auto save\r\n    if( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return;\r\n\r\n    \/\/ if our nonce isn't there, or we can't verify it, bail\r\n    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;\r\n\r\n    \/\/ if our current user can't edit this post, bail\r\n    if( !current_user_can( 'edit_post' ) ) return;\r\n\r\n    \/\/ Make sure your data is set before trying to save it\r\n    if( isset( $_POST['m_meta_description'] ) ) {\r\n        update_post_meta( $post_id, 'm_meta_description', wp_kses( $_POST['m_meta_description'], $allowed ) );\r\n    }    \r\n}\r\n?&gt;<\/pre>\n<p>In the above code, you would change \u201cBox Title\u201d to name the box that all your custom fields will be encased in.<\/p>\n<p>I created a custom field called \u201cm_meta_description\u201d so you can duplicate\/modify that as desired.<\/p>\n<p>Then I created an HTML table to display the multi-line text box for the input of the \u201cmeta description.\u201d Of course, other form elements can be used. A single line text box can be easily swapped in the above code for example.<\/p>\n<p>Ultimately we save the custom values when the post is saved.<\/p>\n<p>That\u2019s it, the code above is all that is needed to display the custom fields (and their values when they exist) and save the values after saving a post.<\/p>\n<p>Now, we can learn how to retrieve the values for use in template files.<\/p>\n<h3>Retrieving Custom Values Within Template Files<\/h3>\n<p>In my example where I created extra boxes for social sharing meta values, I needed to retrieve the values for use in the header between the \u201chead\u201d HTML tags. There are two ways to do that. One is by editing a template file directly to access the values in the custom fields and then display them, and another is to use some WordPress \u201cactions\u201d to \u201cinject\u201d the values between the HTML head tags.<\/p>\n<p>I will show both options here as one may be more appropriate for your situation. You might not need to add anything in the header, but perhaps a sidebar or single post page, so the second set of commands below will offer guidance in those situations.<\/p>\n<p>Here is the code for retrieving the custom values and inserting them into meta tags in between the \u201chead\u201d HTML tags using a WordPress hook. This code can be added to a custom plugin or to the functions.php template file.<\/p>\n<pre>&lt;?php\r\nadd_action('wp_head', 'add_to_wp_head');\r\nfunction add_to_wp_head( )\r\n{\r\n    if (is_single())\r\n    {\r\n        global $post;\r\n        $m_meta_description = get_post_meta($post-&gt;ID, 'm_meta_description', true);\r\n        echo '&lt;meta name=\"description\" content=\"' . $m_meta_description . '\"\/&gt;';\r\n    }\r\n}\r\n?&gt;<\/pre>\n<p>The code would be very similar for retrieving the value in a template file as for including the value in the head with a WordPress hook. I\u2019m not suggesting here though that modifying a theme with custom code is a good idea, because unless you are very organized, you may lose the functionality if you ever update the theme files, or use an entirely different theme.<\/p>\n<p>But perhaps in a pinch you want to get this working until you have more time to write a plugin. Whatever the reason, let\u2019s take a look at how we can get the custom field value from within the\u2026 say, the single.php template file.<\/p>\n<pre>&lt;?php\r\n$m_meta_description = get_post_meta($post-&gt;ID, 'm_meta_description', true);\r\necho 'Here is the meta_description custom field value: ' . $m_meta_description;\r\n?&gt;<\/pre>\n<p>For the above code we are not \u201cinjecting\u201d the code into any of WordPress\u2019s code so there is no need for an \u201caction\u201d or \u201chook.\u201d Also, we already have access to the $post variable providing we are in the loop so there is no need to re-declare it. And of course, there is no need to check if we are looking at a single post since we are executing this code within the single.php file.<\/p>\n<h3>Are There any Other Purposes for These Custom Fields?<\/h3>\n<p>I spoke of why I used these custom fields in WordPress already. Twitter, Facebook, and Google+ being the 3 biggest social sharing networks (arguably), and having a distinct audience (for the most part)\u2026 our content could benefit from being shared in unique ways.<\/p>\n<p>I only touched on it briefly before, but each of the sharing sites, while they may fall back on standard meta data or Open Graph tags, each have a default place that they look to retrieve pertinent information about a given web page.<\/p>\n<p>The most pertinent of the information for a page on the web would be title, description, and image (and maybe video in some cases). Now, each site has different maximums for each of those fields, and they all display images differently, plus like I mentioned, the audience for each is unique. So, it makes sense to use different data for each site, yeah?<\/p>\n<p>Now, as for other reasons to use custom fields\u2026 consider if you use the same sort of data in a post often. As an example, you might create a unique summary for a post when reviewing a restaurant for example. Well, if that summary is in a separate field, it can be shown differently. Perhaps there is different criteria that you review the restaurants based on. Those can now be done in custom fields.<\/p>\n<p>Or what about ingredients for a recipe? When in their own fields they could be used later in different ways, like for sorting.<\/p>\n<p>Or for the affiliate marketers out there, maybe you want to link the featured image to the affiliate product that you are discussing. You can upload the featured image like you would normally do but wrap it in an anchor tag as it gets printed to the screen, using a custom field as the affiliate URL.<\/p>\n<p>The possibilities are endless, and now you are equipped to jump in and test them out for yourself.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I started a new blog several months back and I wanted to include extra boxes on the WordPress edit\/add post screen to provide extra \u201cbehind the scenes\u201d data. More specifically I started to learn more about how meta tags (HTML elements that aren\u2019t shown in the browser unless \u201cviewing source\u201d) can influence what is shown [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0},"categories":[4],"tags":[],"_links":{"self":[{"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/posts\/528"}],"collection":[{"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/comments?post=528"}],"version-history":[{"count":0,"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/posts\/528\/revisions"}],"wp:attachment":[{"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/media?parent=528"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/categories?post=528"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/a1webdesignteam.com\/blog\/wp-json\/wp\/v2\/tags?post=528"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}