• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

nSiteful Web Builders

Building a Better Web - One Site at a Time.

  • Home
  • About
    • Testimonials
    • Resources
  • Web Sites
  • Online Marketing
  • WordPress Support
    • Customized WordPress Training
    • 60-for-60 Sessions
  • Web Applications
  • Blog
    • Archive Listing Minimalistic
    • Blog Articles Grouped by Category
    • Case Studies
    • General
    • Portfolio
    • Reviews
    • Snippets
    • Techniques
  • Contact Jeff
    • Purchase Retainer Consulting Hours
    • About Retainer Consulting Hours

By Jeff Cohan, October 18, 2018

Dive Into WordPress Custom Post Types – Part 2

Last updated November 16th, 2018 at 12:12 pm

dive into preamble

This is one of a series of articles about the why/when/how of WordPress Custom Post Types (CPTs). The articles are geared to WordPress developers who may have little or no experience with custom post types, with the hope that what I share will remove some of the mystery associated with CPTs and encourage some of you to dive right in.

toc for dive into cpt

Posts in this Series

  1. Dive Into WordPress Custom Post Types – Part 1
  2. Dive Into WordPress Custom Post Types – Part 2
  3. Dive Into WordPress Custom Post Types – Part 3

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):

  1. Creating the meta boxes for the custom fields
  2. Adding the HTML for actual form fields
  3. 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.

Related Posts

  1. Dive Into WordPress Custom Post Types – Part 1
  2. Dive Into WordPress Custom Post Types – Part 3
  3. How to use Advanced Custom Fields with Genesis
  4. Use Custom Fields to Hide Stale Posts
  5. Making Sense of WordPress Post Formats
  • Choose the best match.

Written by Jeff Cohan · Categorized: Techniques · Tagged: Advanced Custom Fields, Custom Fields, Custom Post Types, WordPress

  • Choose the best match.

Reader Interactions

Comments

  1. April Wier says

    October 23, 2018 at 8:48 pm

    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.

    Reply
    • Jeff Cohan says

      November 2, 2018 at 1:20 pm

      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.)

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

mailchimp signup

Subscribe to get notified when new articles are published. Unsubscribe any time. No spam. I promise. Check out my newsletter archives.

social

Twitter Facebook LinkedIn

Recent Articles

  • Use Case for Custom Post Type: “In The News” March 10, 2023
  • Create a Custom Shortcode to Display a MemberPress Membership Price ANYWHERE on Your Website February 5, 2023
  • Avoid Direct Styling; Use CSS Instead September 21, 2022
  • Blog Tags: What They Are (and What They’re Not) August 5, 2022
  • How to Create a Simple Custom Events Plugin May 24, 2022

Filter By Category/Tag

Categories

  • Case Studies (7)
  • General (61)
  • Portfolio (5)
  • Reviews (12)
  • Snippets (16)
  • Techniques (38)

Popular Tags

Advanced Custom Fields Blogging Child Themes Content Marketing CSS CSS Grid Customer Service Custom Fields Custom Post Types Diagnostics Facebook FooGallery Genesis Gutenberg HTML Images iPhone Libra Live Chat Marketing Media MemberPress MemberPress Courses mu-plugins MySQL Photo Gallery php Pinterest Plugins Post Formats Pricing Project Management Security SEO Seth Godin Shortcodes Social Networking Surveys Taxonomies Trello Twitter Video Web design Web forms WordPress

siteground wp hosting

Web Hosting

wp101

EasyWordPresstutorialvideosforbeginners.
MemberPress CTA

Footer

Background

Web Sites | WordPress Support | Web Applications.

Formally trained in liberal arts and education (I have a B.A. in Government from Harvard and studied Secondary Education at Rutgers Graduate School), I have honed my skills in the communication arts and sciences as a teacher, trainer, instructional designer, writer, photographer, calligrapher, helpdesk manager, database programmer, and multimedia developer.

(I've also been a group counselor, waiter, bartender, bicycle messenger boy, computer salesman, carpenter's helper, financial analyst, and school board president.)

Tech

Systems since 1983.
Web sites since 1994.
PHP since 2001.
WordPress since 2007.

Contact

770-772-5134
Email Jeff
Send Money
All Ways

Copyright 2023, nSiteful Web Builders, Inc.

 

Subscribe

Pardon the interruption. I know popups can be annoying. But I’d love to have you as a subscriber.

Sign up to be notified when new articles are published. Unsubscribe any time.

* indicates required

Powered by MailChimp

×