clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

How to use: Easy-WordPress-Custom-Post-Types PHP class

An easy way to make: custom post types, custom taxonomies, and custom meta boxes in WordPress by using the helper class Easy-WordPress-Custom-Post-Types.

Installation

You can get the helper class from GitHub.

Then require it in your functions.php file in your WordPress installation:

require "assets/jw_custom_posts.php";

Custom post types

It works pretty much the same as the native WordPress register_post_type method does, by accepting two parameters. As a refresher, here’s the native one:

register_post_type($post_type, $args)

And here’s how to initiate the Easy-WordPress-Custom-Post-Types class. As the example we’ll create a post type called "Works", for a portfolio etc:

$works = new JW_Post_Type('Work', array(
  // What fields and preset metaboxes should be supported.
  'supports' => array('title', 'editor', 'author', 'revisions', 'page-attributes'),

  // Hierarchical means it behaves like a page (not a post), default is `false`.
  'hierarchical' => true,

  // Physical positioning. 5 is just under posts, 0 is above Dashboard.
  'menu_position' => 2
));

Now we got that stored into a variable $works.

See all the parameters it can handle from the WordPress code reference.

Custom taxonomies

Custom taxonomies are easy to initiate:

$works->add_taxonomy('Difficulty');

That creates a non hierarchical taxonomy, the tagging interface. What if you want it to be hierarchal? And just adding s in the end of Difficulty does not make it plural. You can pass as many arguments to it as you like and the second parameter is the plural name of the taxonomy.

$works->add_taxonomy('Difficulty', 'Difficulties', array(
  'hierarchical' => true
));

See the WordPress code reference for all the parameters it can handle.

Custom meta boxes

And here’s how to create the metaboxes:

$works->add_meta_box('Snippet Info', array(
  'GitHub Link'      => 'text',
  'Additional Notes' => 'textarea',
  'Original Snippet' => 'checkbox',
  'Snippet Image'    => 'file',
  'Favorite Food'    => array( 'select', array('pizza', 'tacos') )
));

You don’t have control over the HTML that is inside the boxes, but doing them like this is really easy! You can get them up and running in just few minutes. If you want more control over the boxes consider using the WP Alchemy MetaBox class.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!