Last updated November 16th, 2018 at 12:12 pm
In Part 1 of this series, I introduced the idea of using Custom Post Types and Custom Fields for presenting certain types of content on your Web site. I also discussed the pitfalls of using the standard post or page editors as workarounds.
In this article, I talk about…
The Intimidation Factor
Custom post types and custom fields can be intimidating because the code needed to create them looks complicated.
Code for setting up a Custom Post Type
Here’s an example from the WordPress Codex for defining and establishing (i.e., registering) a custom post type for books:
add_action( 'init', 'codex_book_init' ); /** * Register a book post type. * * @link http://codex.wordpress.org/Function_Reference/register_post_type */ function codex_book_init() { $labels = array( 'name' => _x( 'Books', 'post type general name', 'your-plugin-textdomain' ), 'singular_name' => _x( 'Book', 'post type singular name', 'your-plugin-textdomain' ), 'menu_name' => _x( 'Books', 'admin menu', 'your-plugin-textdomain' ), 'name_admin_bar' => _x( 'Book', 'add new on admin bar', 'your-plugin-textdomain' ), 'add_new' => _x( 'Add New', 'book', 'your-plugin-textdomain' ), 'add_new_item' => __( 'Add New Book', 'your-plugin-textdomain' ), 'new_item' => __( 'New Book', 'your-plugin-textdomain' ), 'edit_item' => __( 'Edit Book', 'your-plugin-textdomain' ), 'view_item' => __( 'View Book', 'your-plugin-textdomain' ), 'all_items' => __( 'All Books', 'your-plugin-textdomain' ), 'search_items' => __( 'Search Books', 'your-plugin-textdomain' ), 'parent_item_colon' => __( 'Parent Books:', 'your-plugin-textdomain' ), 'not_found' => __( 'No books found.', 'your-plugin-textdomain' ), 'not_found_in_trash' => __( 'No books found in Trash.', 'your-plugin-textdomain' ) ); $args = array( 'labels' => $labels, 'description' => __( 'Description.', 'your-plugin-textdomain' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'book' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ) ); register_post_type( 'book', $args ); }
That’s a whole lot of code. But you don’t really need all of it. Here’s the basic version, from the same page in the Codex:
function codex_custom_init() { $args = array( 'public' => true, 'label' => 'Books' ); register_post_type( 'book', $args ); } add_action( 'init', 'codex_custom_init' );
Either one of those versions of code will create a new post type for Books and add the new post type to the WordPresss dashboard.
Code for setting up Custom Fields
As for the code for creating custom fields (accomplished by creating and defining what WordPress calls meta boxes), the intimidation factor is even greater. You need code for the following (examples are slightly modified versions from this page in the WordPress Codex):
- Creating the meta boxes for the custom fields
- Adding the HTML for actual form fields
- Saving the meta box form input
Note that for the purpose of simplicity, the examples omit code you would want to implement for security purposes in a live site.
Step 1. Create the meta box for the custom fields. This code will indicate which post type(s) will display the new meta box. It will also provide the name of the callback function, whose code will output the HTML contents of the meta box. The following code creates a meta box that will show up on the edit screens for posts and for a hypothetical custom post type named wporg_cpt.
function wporg_add_custom_box() { $screens = ['post', 'wporg_cpt']; foreach ($screens as $screen) { add_meta_box( 'wporg_box_id', // Unique ID 'Custom Meta Box Title', // Box title 'wporg_custom_box_html', // Content callback, must be of type callable $screen // Post type ); } } add_action('add_meta_boxes', 'wporg_add_custom_box');
Line 2 defines the post types for which the meta box will show up.
Line 12 invokes this function, hooked to the WordPress add_meta_boxes
action.
Step 2. Add form field(s) to the meta box. Do this by creating the callback function (referenced in Line 7 of the above code) that outputs the meta box. This example contains only one form field, a drop-down list. The name of the function is the third parameter of the above function, which created the meta box.
function wporg_custom_box_html($post) { $value = get_post_meta($post->ID, 'wporg_field', true); ?> <label for="wporg_field">Description for this field</label> <select name="wporg_field" id="wporg_field" class="postbox"> <option value="">Select something...</option> <option value="something" <?php selected($value, 'something'); ?>>Something</option> <option value="else" <?php selected($value, 'else'); ?>>Else</option> </select> <?php }
Note that line #2 retrieves the saved value of the form field, if any. Then, lines 7 and 8 use the WordPress selected() function to preselect the relevant option. Note also that this code switches between php and HTML.
Step 3. Save the meta box form input. This sample code saves custom field values using the update_post_meta()
WordPress function.
function wporg_save_postdata($post_id) { if (array_key_exists('wporg_field', $_POST)) { update_post_meta( $post_id, '_wporg_meta_key', $_POST['wporg_field'] ); } } add_action('save_post', 'wporg_save_postdata');
Yeah, a lot of code. But don’t be intimidated, because…
Tools to the Rescue!
Don’t let the intimidation factor intimidate you. The good news is you do not have to code custom post types and custom fields by hand. There are many excellent tools (many of which are free) that take the pain away.
My current go-to tools are:
- GenerateWP, an online tool for generating all the code you need for registering custom post types. The free version gives you access to 28 basic generators. If you sign up for the paid plan, you get access to 5 additional premium generators.
- Advanced Custom Fields. I use the Pro version, and I highly recommend it. For a one-time payment of $100, you get lifetime access to all premium features for an unlimited number of Web sites. (For only $25, you get all premium features for 1 Web site.) The free version can be downloaded/installed from the WordPress plugin respository.
I plan to cover the details on how to use these tools — as well as provide information about other tools — in future blog articles.
Displaying Custom Post Types and Custom Fields on the Front End
Ok. So the tools listed above can handle the backend of creating custom post types. But you’re probably wondering how to display these custom post types, along with their custom fields, on the front end of your site. Well, as you might have guessed, this, too is a topic for future posts.
Join The Discussion
Please post your questions and comments in the comments section below.
Let me know if you’re interested future additional posts about custom post types and custom fields.
Also, if you have some content type you think might be a good candidate for custom post types and custom fields, share your thoughts. I might use your use case in a future blog post — or even a tutorial!
Summary
Custom Post Types and Custom Fields can be intimidating. But they don’t have to be. There are tools to make the job easier. And the power and flexibility you’ll enjoy from using these WordPress features will make you glad to took the plunge.
I can’t wait to see you cover ACF. It is on my to-do list to conquer. I know once I really understand it, it will open up so much more value I can deliver to my clients.
April –
Thanks for the reply.
I’m working on it (the “ACF” stuff)!
(Consider signing up for my email newsletter to make sure you get timely notification.)