Tuesday, November 1, 2016

How to Create Custom WordPress Write/Meta Boxes




Creating meta boxes is a crucial part of WordPress theme/plugin development. It's a way to add an appealing editor to the post screen and avoids forcing users to rely on custom fields. If you've ever created a custom post type in WordPress, you've probably wanted to add some sort of additional data to it. Sure, you could use custom fields, but that's ugly. Getting started with custom meta boxes is easy, so let's dive in!











A custom meta (or write) box is incredibly simple in theory. It allows you to add a custom piece of data to a post or page in WordPress.

Imagine that you're working on a theme for a client that wants to catalog his extensive collection of concert posters. You immediately start looking to the core WordPress functionality to see how you might organize the theme: Every post will represent a poster, which is perfect for adding an image, title and description. We can also use the categories and tags system inside of WordPress to organize the posters. But what if we wanted to add a new type of meta data for the "artist" of each poster? Hmph. WordPress doesn't quite have anything for that right out of the box... which brings us to custom meta boxes.

A custom meta (or write) box is incredibly simple in theory. It allows you to add a custom piece of data to a post or page in WordPress - what's better is that it can fit directly into most of the default pages inside WP, so you can easily place it inside the Post-Editor for easy use by non-technical types. As I said in the intro, you can add this same kind of "meta data" to your post using the built in custom fields for a post or page. There's nothing wrong with this persay, but it's not a very graceful or user-friendly.

Instead, you want to create a custom meta box that contains fields for all of your data and saves all of that stuff right when the post is published. That's what we're covering here. This is broken down into three big steps:

  • Adding the meta box

  • Rendering the meta box

  • Saving the data (the right way - yes, there is a wrong way)


It's worth noting that a lot of this information can also be used inside the custom post types API (we'll get to that point later!), but for the sake of keeping things focused today, we're going to add this directly to the default post editor.

For the advanced readers in the audience: Yes, custom post types is where we'll be going with this eventually, but it's important to setup some fundamentals first. Plus, as you can use the custom meta boxes in all sorts of places, it's good for anyone to know.

Anything in this tutorial will work in a theme's functions.php file. That is not the correct place for it, however. If you're adding data to a post, chances are you want it there regardless of your front end design. As such, you should place this code some place that isn't dependent on your design: a plugin file.

The Meta Box Title

Conveniently, WordPress provides a function for adding meta boxes to a given admin screen: add_meta_box.

The codex entry is well done for this function, but here's a brief overview. Its prototype:



$id is the html ID attribute of the box. This is useful if you're loading custom CSS or Javascript on the editing page to handle the options. Otherwise, it doesn't really matter all that much.

$title is displayed at the top of the meta box.

$callback is the function that actually renders the meta box. We'll outline this in step 2.

$page is where you want the meta box to be displayed. This should be a string with 'post' or 'page' or 'some_custom_post_type'.

$context is where you want the meta box displayed. 'normal' puts it below the post editor. 'side' moves the meta box to editing screen's right sidebar (by the categories and tags, etc). 'advanced' also put the box in the same column as the post editor, but further down.

$priority tells wordpress where to place the meta box in the context. 'high', 'default' or 'low' puts the box closer to the top, in its normal position, or towards the bottom respectively. Since all meta boxes are drag-able, $priority is not a huge deal.

Finally $callback_args lets you pass data to your $callback function in the form of an array. We're not going to use this here, but it could be useful for passing some data to the meta box. Say, if your plugin had several options that influenced what was displayed in the meta box. You could pass those options values through the $callback_args array.

So, our add_meta_box call will look like this:



We can't just pop this into our plugin file alone. Doing so will result in the white screen of death, and PHP fatal error: call to undefined function. Why? Because we called add_meta_box function before WordPress was loaded. So we need to use a WordPress hook, which is part of the plugin api. Basically, functions get hooked into a given WordPress action or filter hook, then those functions are fired when that hook loads. By wrapping our add_meta_box call in a function, then hooking that function into the add_meta_boxes action hook, we avoid the fatal error.

Our code to add the meta box to our post screen would look like this:




The above code is enough to add the meta box, but now we have to render the thing and actually add fields. This is just an HTML form code mixed in with a bit of PHP to display the saved data. We don't need to include the form tags as WordPress does that for us.

Remember the string we passed as the $callback in add_meta_box? We're now going to create a function with the same name. This function will take care of all the display inside the meta box.




We're going to add several fields to our meta box: a text input, a drop down menu, and a check-box. Let's start with the text input.





But what about actually displaying the data? Well, as you'll see in step 3, we'll store this data in the wp_postmeta table using the update_post_meta function. That function has two sister functions called get_post_meta and get_post_custom, which grab data from wp_postmeta. get_post_meta only grabs data from one key, while get_post_custom grabs all of it. Because we're only really using one field at this point, let's use get_post_meta.

Also note that the add_meta_box function passes one variable to our callback: $post, which is a post object.







With the addition of a second field, we changed or get_post_meta call to get_post_custom, which returns an associative array of all the post's custom keys and values. We then just access our fields via their names. The ternary statements keep our code from throwing PHP warnings (undefined indices and such). We'll cover the esc_attr function in step three.

In the drop down, we're going to use one of WordPress's most handy functions: selected. This compares the first value, the data we saved, with the second, the <option>'s value attribute. If they're the same, the function will echo selected="selected", which makes that value display on the drop down. Pretty sweet, and it saves us from writing a bunch of if or ternary statements. You can also use the selected() function with radio buttons.




Again WordPress provides the handy function checked(). It works just like selected() comparing the first value (our saved data) to the second and echoing out checked="checked" if they're the same.

wp_nonce_field adds two hidden fields to our meta box. One of them is a nonce. These are random strings of numbers that are valid on per user per blog basis for 24 hours. Nonces are a way of verifying intention, and they make sure that WordPress doesn't do anything unless the request came from a very specific place. In other words, we don't want to accidentally update our data by somehow running our save function (see step 3) in another location other than the save_post hook, so we check to make sure the nonce is valid before doing anything.


The number one rule when putting anything into your database or on your site isdon't trust the user. Even if that user is you.

To save our data, we're going to rely on another WordPress hook: save_post. This works just like our action hook above:



The cd_meta_box_save function will receive one argument, the post id, and take care of cleaning and saving all of our data. The save_post hook fires after the update or save draft button has been hit. So we have access to all the $_POST data, which includes our meta box fields, within our saving function. Before we can do anything, however, we have to do three things: check if the post is auto saving, verify the nonce value we created earlier, and check to make sure the current user can actually edit the post.



Now the fun stuff: actually saving our data. The number one rule when putting anything into your database or on your site is don't trust the user. Even if that user is you. To that end, before we save any data, we want to make sure there's nothing malicious in there. Fortunately WordPress provides a bunch of functions for data validation.

You already saw esc_attr() above (step 2). This one encodes ' " and < > into HTML entities. Why use this? So users couldn't type a <script> into your meta box. If you'd like to allow certain HTML tags in, but strip others, wp_kses can do that. It takes two arguments, the first of which is the string you'd like to check and the second is an associative array of allowed tags. WordPress provides many more data validation tools, just don't be afraid to use them.

We're going to use the update_post_meta function to date care of saving our data. It takes three arguments: a post ID, the meta key, and the value.





That's it! You should have a fully working meta box. Other examples you may find around the web loop through a bunch of fields without really cleaning the data. This is the wrong approach. Always use the built in data validation functions; different fields/values may require different data validation.

To use these custom fields on the front end of your site, use the get_post_meta or get_post_customfunctions (see step 2).





General Catalyst-backed Octane will make you a bot

Bots are hot. Ever since Facebook introduced chatbots at F8 last spring, they’ve been integrated into brand pages for customer service, e-commerce and fun.


But, how do you make a bot? Many businesses don’t have developers that are adept at creating them.


Enter Octane, a newly-formed startup launched by media personality Ben Parr, serial entrepreneur Matt Schlicht and Omegle founder Leif K-Brooks. The team has already built up a following in the bots community after creating a popular Facebook group and a digital magazine.


Their business is like web design platforms Wix or Weebly, but for chatbots. It’s a paint-by-numbers for bot creation that’s so easy, I could do it. (I did it! I programmed the Katie Roof bot to respond with “raise the roof” as my greeting. Sorry but not sorry).


Phil Libin, co-founder of Evernote and partner at General Catalyst, talked about why they led a $1.5 million funding round in Octane. Bots are a “very natural way to interact with technology,” he said, voicing optimism about the founders because he’s “impressed with the community they’ve already already managed to build.”





With an impactful client list that already includes 50 Cent and Aerosmith, the Octane team hopes to double down on its Facebook business, eventually expanding to SMS, iMessage, Slack and websites.


“We believe this is something that everyone’s going to need, not just top enterprises,” said Schlicht.


Believing that bots are more than just a gimmick, Parr says “this actually saves you time. This actually makes you money.” It’s a “very clearly a win for every business that uses it.”


Controversial crime reporting app Vigilante banned from App Store

A controversial crime-reporting app called Vigilante has been justifiably been kicked out of the App Store for an app that encouraged, well – vigilantism – and led to the potential for violent responses and racial profiling. The app had only been live for a week in New York before getting the boot, after promising a tool that opened up the 911 system, bringing near real-time reports of criminal activity to its digital display.


The app didn’t just encourage you to avoid the problematic area – a solution that alone would have been questionable, due its similarity with the unfortunate series of apps that have launched over the years, promising to help you avoid “sketchy” or “poor” neighborhoods. These apps can reinforce assumptions people make about race and income level contributing to crime, and have been called out repeatedly for their racial and classist undertones.


In addition to this issue, Vigilante actively encouraged its users to get involved when they received a crime report. A quote on its launch blog post even suggested that “average and ordinary” citizens should approach the crime problem “as a group” and see what they can do.


Therefore, the app could easily be turned into a tool that could encourage users to intimidate and harass innocent people, because they happened to be in an area where the crime was reported, and matched some sort of profile in the end user’s mind of what a criminal should look like.


We’ve already seen the issue of rampant racial profiling in the neighborhood app Nextdoor, which recently had to roll out a new system to clamp down on the issue, by forcing users to enter in physical descriptions – like clothing, hair color, shoes, etc. – if they choose to include the race of the person in their report. Meanwhile, the same sort of profiling takes place on closed Facebook neighborhood groups, largely unchecked.


In a report from The Guardian, Sam Gregory, program director of Witness, an organization trains and supports activists to document human rights violations, cautioned about the app’s framing. “Vigilantism is a very different idea to being an ethical witness to what’s happening,” he said.




Apple doesn’t typically comment on app removals, but it’s fair to say that the app was likely removed because of the clause in Apple’s App Developer Review Guidelines which bans apps that encourage or risk physical harm.


The developer of the app, a company called Sp0n, said it’s working with Apple to resolve the issue and still plans on shipping a version of the app on Android.




Microsoft Teams, its new Slack rival, is launching today as part of Office 365

Microsoft is holding a big event today to unveil what many expect will be its new Slack competitor. Ahead of that, it has posted a unlisted video on YouTube that spills some of the beans. The product will officially be called Microsoft Teams, it will be a part of Office 365, and it is part of the company’s big push to create a new generation of enterprise products that appeal, in Microsoft’s own words, to people from “different cultures and generations.”


From the video, embedded below, it looks like Microsoft is launching Teams with several features right out of the box. First, for those of you who might already use Slack and Hipchat, it’s notable that Teams looks like it will include the ability to have threaded comments, where you can reply inline in a conversation — a feature that Slack, for one, has said for a long time now that it has been working on but has yet to include.


It will also include video chat services, along with expected integration with Microsoft’s services. What’s less clear is how it will integrate with other products. An open letter to Microsoft published today by Stewart Butterfield, the CEO of Slack, weighs heavily on the open source aspect, an area where Microsoft has not been known to excel in enterprise software in the past.


Slack’s team collaboration platform has been a runaway, surprise success in the market, tapping into a need for people to chat with each other on a platform where they can also call in all kinds of other apps that they might use to get their work done, or to distract each other, by way of shortcuts using slash commands. The company last week reported that it now has 1.25 million paying users — you pay for added features and more storage of your messages — although from a closer look it appears that growth may be slowing right now, which points to an opportunity for others to move in on space that Slack has come to own in terms of mindshare.




Like Facebook’s Workplace, another Slack and Hipchat competitor that launched recently, Microsoft Teams is going live with a number of key customers already signed on, some of whom are featured in the video. They include Accenture with 400,000 employees and Hendrick Motorsports, the racing company.


We’ll be live at the event and updating from there. For a preview, see the video below:


Waterloo wows with demo of first working Hyperloop air levitation system

The University of Waterloo has a team dedicated to making a real, working pod system for the ambitious Hyperloop transportation system envisioned by Tesla founder Elon Musk. The so-called ‘Waterloop,’ (bonus points for puns) got a test run yesterday, making the team the first to demonstrate a functioning, pneumatic levitation system on a test track using nothing but air to gloat their test objects.



The @waterloo_hyper team shows the world's first functional pneumatic hyperloop levitation system! #WaterloopLevitates#UWaterloo#cdnpsepic.twitter.com/u9CCiOh0rM


— University Waterloo (@UWaterloo) November 2, 2016



It was a scaled down test, and still a far cry from a pod capable of actually transporting humans, but it’s a sign that the 120-strong team of engineering students is on the right track (hope someone is conferring bonus points on me for puns, too). Successfully using air to levitate a car-like object on a track is a big achievement (even when propelled by team members as in the demo above) and one that could lead to decreased cost and friction. This could make it a lot easier for future production Hyperloop systems to achieve the ambitious high speeds they’re aiming for.




Waterloo’s Waterloop team is still in the running among 22 teams competing in a SpaceX-run competition designed to bring out the best in Hyperloop pod design. Said competition is currently set for January 2017, and will take place at SpaceX HQ in Hawthorne, California. Between now and then, the Waterloo team has a lot to get done, and will now focus on their own test track facility at Kitchener’s Lot 41 innovation center in Canada.


Waterloop is funding its project in part via Kickstarter, and while it’s achieved its goal, there’s still time to contribute if you’re looking to help propel Hyperloop transportation research forward.


Glide’s Apple Watch band has two cameras

Remember Samsung’s original Galaxy Gear watch? It’s all right if you say don’t. It was big – in the sense of being physically large, due in part to the inclusion of a camera in the bezel/strap. The company was clearly looking to jam all of the functionality possible into the device and came out the other side with an extremely large product.


That’s likely a big part of why the functionality hasn’t been considered standard in subsequent devices. That and the fact that he world still needed convincing that the smartwatch was a viable space. Built-in photos and videos just seemed like overkill.


Now video messaging service Glide, of all companies, is bringing that functionality to Apple watch with CMRA, a band that has not one, but two cameras built in. Because if you’re going to go for it, go for it, right?


unspecified-1




The purpose behind a pair of cameras is to the offer the same front- and rear-facing functionality you get on a smartphone. After all, Glide is a video messaging service, so selfie video is of the utmost importance here. The cameras are two- and eight-megapixels, respectively and are capable of doing both stills and video.


The band also brings some added firepower to the fight, with a bonus battery that can do 100 photos or 30 minutes of video on a charge. CMRA goes up for pre-order today, priced at $149, which includes a dock that’ll charge the watch and band all at the same time.

Turner’s streaming service for film geeks, FilmStruck, goes live

FilmStruck, a new streaming service aimed at film geeks developed by Turner Classic Movies, has now launched. Announced earlier this year for a mid-October arrival, the service belatedly debuted with a collection of hundreds of classic, indie, foreign, and cult film, as promised. The company also announced the pricing for its new Netflix-like competitor: a somewhat costly, comparatively speaking, starting at $7 per month.


An expanded version of the service for $10.99 will include the base collection of hundreds of movies as well as the Criterion Channel, which represents the largest collection of Criterion films available for streaming with its 1,200 titles. Those films will be exiting Hulu on November 11, where they have previously been hosted. This collection includes studio classics and contemporary films, along with their special features like filmmaker profiles, masterclasses, and curated series by guests.


This top subscription tier is also available as an annual subscription for $99.00.


screen-shot-2016-11-02-at-9-47-14-am


It’s worth noting that FilmStruck’s entry-level pricing only a dollar less than Netflix’s cheapest “Basic” plan. Though reasonable as a standalone fee, when you take into consideration that many people today are already paying for Netflix, HBO NOW, and/or Hulu, and possibly have access to Prime Video through their Amazon Prime annual subscription, FilmStruck could have limited appeal.


Then again, that may be what it’s after. The service is largely designed to cater to those who mainly watch movies – something that many of the streaming services, and especially Netflix, don’t have as much of these days. In fact, a report from this March by AllFlicks found that the number of Netflix movies in its catalog had dropped by 33 percent over the course of two years. Of course, these days Netflix is investing in its own original content, including movies, but not enough to bring those numbers back up.




On FilmStruck, there are plenty of movies to watch, if you prefer a certain sort of genre that doesn’t include today’s hit blockbusters. Instead, you can browse titles like “A Hard Day’s Night,” “Mad Max,” “Metropolis,” “Moulin Rouge,” “My Life as a Dog,” “Paths of Glory,” “The Player,” “Seven Samurai,” “A Room With A View,” “Blood Simple,” “The Unbearable Lightness of Being,” “Stardust Memories,” “Breathless,” and many others.


Participating studios include Janus Films, Flicker Alley, Icarus Films, Kino, Milestone, Zeitgeist, Film Movement, Global Lens, First Run Features, Oscilloscope Laboratories, Shout Factory, as well as major studios MGM and Warner Bros.


The service is available now, free for the first 14 days during a trial period. The movies can be streamed across desktop, mobile, Amazon Fire TV, Apple TV (4th gen.) and soon, Chromecast and Roku.