A PHP Class for creating Wordpress Custom Post Types easily

Overview

N.B I've released an updated version of the project to a new repository, PostTypes.

WP Custom Post Type Class v1.4

Latest Stable Version Total Downloads License

A single class to help you build more advanced custom post types quickly.

Installation

Install with Composer

Add the package to your projects composer.json file. Visit getcomposer.org more information.

{
    "require": {
        "jjgrainger/wp-custom-post-type-class": "dev-master"
    }
}

Install Manually

Download and include the class file into your themes functions.php like so:

include_once('CPT.php');

and your ready to roll!

Creating a new Custom Post type

To create the post type simply create a new object

$books = new CPT('book');

The first parameter is the post type name and is required. ideally the post type name is all lowercase and words separated with an underscore _.

to be specific about other post types names you can pass an associative array:

post_type_name - the name of post type (singular, lowercase, underscores)

singular - the singular label of the post type (Book, Person)

plural - the plural of the post type (Books, People)

slug - the permalink slug for the post type (plural, lowercase, hyphens)

you pass these names through the first parameter as an array like so:

$people = new CPT(array(
	'post_type_name' => 'person',
	'singular' => 'Person',
	'plural' => 'People',
	'slug' => 'people'
));

The optional second parameter is the arguments for the post_type. see WordPress codex for available options.

The Class uses the WordPress defaults where possible.

To override the default options simply pass an array of options as the second parameter. Not all options have to be passed just the ones you want to add/override like so:

$books = new CPT('book', array(
	'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

See the WordPress codex for all available options.

Existing Post Types

To work with exisiting post types, simply pass the post type name into the class constructor

$blog = new CPT('post');

Adding Taxonomies

You can add taxonomies easily using the register_taxonomy() method like so:

$books->register_taxonomy('genres');

this method accepts two arguments, names and options. The taxonomy name is required and can be string (the taxonomy name), or an array of names following same format as post types:

$books->register_taxonomy(array(
	'taxonomy_name' => 'genre',
	'singular' => 'Genre',
	'plural' => 'Genres',
	'slug' => 'genre'
));

Again options can be passed optionally as an array. see the WordPress codex for all possible options.

Existing Taxonomies

You can add exisiting taxonomies to the post type by passing the taxonomy name through the register_taxonomy method. You will only need to specify the options for the custom taxonomy once, when its first registered.

Admin Edit Screen

Filters

When you register a taxonomy it is automagically added to the admin edit screen as a filter and a column.

You can define what filters you want to appear by using the filters() method:

$books->filters(array('genre'));

By passing an array of taxonomy names you can choose the filters that appear and the order they appear in. If you pass an empty array, no drop down filters will appear on the admin edit screen.

Columns

The Class has a number of methods to help you modify the admin columns. Taxonomies registered with this class are automagically added to the admin edit screen as columns.

You can add your own custom columns to include what ever value you want, for example with our books post type we will add custom fields for a price and rating.

This class doesn't have any methods for adding custom fields as Advanced Custom Fields (ACF) is way more awesome than anything this class could do!

You can define what columns you want to appear on the admin edit screen with the columns() method by passing an array like so:

$books->columns(array(
	'cb' => '<input type="checkbox" />',
	'title' => __('Title'),
	'genre' => __('Genres'),
	'price' => __('Price'),
	'rating' => __('Rating'),
	'date' => __('Date')
));

The key defines the name of the column, the value is the label that appears for that column. The following column names are automagically populated by the class:

  • any taxonomy registered through the object
  • cb the checkbox for bulk editing
  • title the post title with the edit link
  • author the post author
  • post_id the posts id
  • icon the posts thumbnail

Populating Columns

You will need to create a function to populate a column that isn't automagically populated.

You do so with the populate_column() method like so:

$books->populate_column('column_name', function($column, $post) {

	// your code goes here…

});

so we can populate our price column like so:

$books->populate_column('price', function($column, $post) {

	echo "£" . get_field('price'); // ACF get_field() function

});

The method will pass two variables into the function:

  • $column - The column name (not the label)
  • $post - The current post object

These are passed to help you populate the column appropriately.

Sorting Columns

If it makes sense that column should be sortable by ascending/descending you can define custom sortable columns like so:

$books->sortable(array(
	'column_name' => array('meta_key', true)
));

The true/false is used to define whether the meta value is a string or integer, reason being is that if numbers are ordered as a string, numbers such as:

1, 3, 5, 11, 14, 21, 33

Would be ordered as:

1, 11, 14, 21, 3, 33, 5

By adding the option true value the values will be sorted as integers, if false or undefined, the class will sort columns as string.

so for our books example you will use:

$books->sortable(array(
	'price' => array('price', true),
	'rating' => array('rating', true)
));

Menu Icons

Dashicons

With WordPress 3.8 comes dashicons an icon font you can use with your custom post types. To use simply pass the icon name through the menu_icon() method like so:

$books->menu_icon("dashicons-book-alt");

For a full list of icons and the class names to use visit https://developer.wordpress.org/resource/dashicons/

Translation

The class is setup for translation, but if you need to set your own textdomain to work with your theme or plugin use the set_textdomain() method:

$books->set_textdomain('your-textdomain');

Flush Rewrite Rules

You can programmatically recreate the sites rewrite rules with the flush() method. This is an expensive operation and should be used with caution, see codex for more.

$books->flush();

Notes

Author

Joe Grainger

Comments
  • PHP Warning in add_admin_columns

    PHP Warning in add_admin_columns

    I'm getting the following warnings:

    PHP Warning: in_array() expects parameter 2 to be array, null given in [theme]/inc/CPT.php on line 591 PHP Warning: in_array() expects parameter 2 to be array, null given in [theme]/inc/CPT.php on line 593

    I'm just using this in a pretty basic way, not adding any taxonomies to my CPT. Should this check if there are any taxonomies to work with earlier? (currently does this on :611)

    opened by madysondesigns 9
  • Custom taxonomies not registering?

    Custom taxonomies not registering?

    I may be missing something here.. Wordpress is something I only touch a couple times a year, so I'm very rusty.

    I have an $options array defined, then:

    $staff = new CPT('Staff Member', $options);
    $staff->register_taxonomy('departments');
    

    That should work, correct? Or is it more involved than this? It's not adding the "Staff Members -> Departments" menu option in the Wordpress ui at all. I can add the existing "Categories" taxonomy to post types, but registering new ones doesn't seem to do anything.

    No error messages or anything, so I get the vibe that I'm overlooking a step. I've also tried calling it via the $options taxonomies array too, but no success there either..

    Thanks ahead of time

    opened by loremipson 9
  • Using with previously registered post types.

    Using with previously registered post types.

    Can I use this class with already registered post types, such as 'Posts'. I would like to use the class to register taxonomies and use the other features.

    opened by matthewsoares 9
  • Textdomain usage and WordPress coding standards

    Textdomain usage and WordPress coding standards

    Updated the class to make use of the textdomain, added a constructor param for this, non-optional. Also updated the code to follow the WordPress Core Handbook coding standards (https://make.wordpress.org/core/handbook/coding-standards/), simply because it's good practice. Also updated the readme.md to reflect the changes made.

    opened by ghost 8
  • Display custom post type tags

    Display custom post type tags

    How do I display custom-post-type tags?

    I have created custom-post-type and register "members" and I am trying to display that members_tags.

    $member = new CPT(array(
        'post_type_name' => 'members',
        'singular' => __('Members', 'c2s'),
        'plural' => __('Members', 'c2s'),
        'slug' => 'Members'
    ),
       array(
        'supports' => array('title', 'editor', 'thumbnail', 'comments'),
        'menu_icon' => 'dashicons-groups'
    ));
    
    $member->register_taxonomy(array(
        'taxonomy_name' => 'members_tags',
        'singular' => __('Members Tag', 'c2s'),
        'plural' => __('Members Tags', 'c2s'),
        'slug' => 'member-tag'
    ));
    

    members_tags

    opened by rabinrai44 6
  • Issuse: Atribute panel no showing parent select

    Issuse: Atribute panel no showing parent select

    First of all thx for the code :)

    When the custom post is created i can´t get the hierarchy to work properly.

    image

    The 'Parent' select does not show up ( And yes, i do have more than one post of the same post-type )

    image

    Thanks for all.

    opened by ghost 6
  • sortable doesn't work

    sortable doesn't work

    The sortable doesn't seem to work for me. When I click any of the sorting columns (price or rating) it just returns blank list. screen shot 2014-01-21 at 5 35 26 pm screen shot 2014-01-21 at 5 35 43 pm screen shot 2014-01-21 at 5 36 53 pm

    Did I miss something?

    opened by owldesign 6
  • Error when defining taxonomies

    Error when defining taxonomies

    Hi,

    First off all, thanks for the code. Registering post types is a breeze but when registering taxonomies, it returns this error:

    Fatal error: Call to a member function add_rewrite_tag() on a non-object in .../wp-includes/rewrite.php on line 51
    

    I am using WordPress 3.7.1 by the way.

    bug 
    opened by dinolatoga 6
  • Needs a has_archive flag

    Needs a has_archive flag

    I frequently disable the CPT archive and use a custom page template instead - basically any time the classic blog list format doesn't apply.

    Will try to hack it in real quick but if I submit a pull request, it may not be how you'd do it within your structure.

    opened by isarmstrong 5
  • Could not translate

    Could not translate "Add New" label

    Is it a typo that you wrote:

    'add_new' => _('Add New'),
    

    I use WPML and could not translate this label. If I change it manually to

    'add_new' => __('Add New'),
    

    I can translate the label.

    opened by danielbehrendt 5
  • Add menu_position

    Add menu_position

    Tried to add the CPT higher on the menu.

    function menu_position( $position = 5) {
        $this->options["menu_position"] = $position;
    }
    

    This works.

    opened by WebbizAdmin 4
  • Unable to sort on menu_order

    Unable to sort on menu_order

    Hi,

    I have added the menu_order to the admin screen for a CPT. I can make the column sortable and display the values inside the column. However when I click the column header to sort, the sorting action displays an empty list. Can't figure out what is going wrong here:

    	'cb' => '<input type="checkbox" />',
    	'title' => 'Title',
    	'video_type' => 'Type',
    	'menu_order' => 'Order',
    	'sticky' => 'Sticky',
    	'date' => 'Date',
        ));
        $videoPost->sortable(array(
    	'sticky' => array('sticky', false),
    	'menu_order' => array('menu_order', true),
        ));
        $videoPost->populate_column('menu_order', function($column, $post){
    	echo $post->menu_order;
        });
        $videoPost->populate_column('video_type', function($column, $post){
    	echo ucfirst(get_field('video_type'));
        });
        $videoPost->populate_column('sticky', function($column, $post){
    	if(get_field('sticky')) {
    		echo 'Yes';
    	}
        }); 
    
    Thank you,
    Sander
    opened by sanderdewijs 0
  • Adding post_row_actions

    Adding post_row_actions

    Hello:

    Thank you for the great work on this class. Makes setup and config so much easier for us. I was wondering if there's a way to add post_row_actions to a custom column? I have a CPT for 'people' that is not using the default post title, and instead I've created a column that displays last_name, first_name and I'd like to have row actions (pictured) available on hover if possible.

    Thanks for any help you can offer.

    screen shot 2016-11-01 at 1 38 24 pm

    opened by nateluzod 0
  • Changing the bulk actions

    Changing the bulk actions

    I would say your class is fantastic. I am very satisfied using CPT Class. I would like to know if it might be possible to implement some methods to change the navigation of bulk-action-selector-top, or the actions of the date filter selector. Example: Show ACF datepicker in the dropdown date filter.

    opened by marlonleite 0
  • How to translate post type name

    How to translate post type name

    i don't know if i'm doing something wrong but i'm not able to translate the name of the post type/taxonomy... not the 'Add New' label but the singular and plural names of the post type/taxonomy (ie: my CPT singular name is "Brands" and i want to translate "Brands").

    this is the way i'm registering the post type

    // Register Brand custom post type
    $brand = new CPT(
        // Names
        array(
            'post_type_name'    => 'brand',
            'singular'          => 'Brand',
            'plural'            => 'Brands',
            'slug'              => 'brands'
        ),
        // Options
        array(
            'has_archive'           => true,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'revisions'),
            'exclude_from_search'   => true,
            'map_meta_cap'          => true,
            'capabilities'          => array(
                'edit_post'             => 'edit_brand',
                'edit_posts'            => 'edit_brands',
                'edit_others_posts'     => 'edit_other_brands',
                'publish_posts'         => 'publish_brands',
                'read_post'             => 'read_brand',
                'read_private_posts'    => 'read_private_brands',
                'delete_post'           => 'delete_brand'
            )
        )                 
    );
    // Icon
    $brand->menu_icon('dashicons-star-filled');
    // Translation
    $brand->set_textdomain('my-text-domain');
    
    

    i also tried using WordPress translation functions in the names section like so:

        array(
            'post_type_name'    => 'brand',
            'singular'          => __('Brand'),
            'plural'            => __('Brands'),
            'slug'              => 'brands'
        ),
    

    and with adding a text domain name

        array(
            'post_type_name'    => 'brand',
            'singular'          => __('Brand', 'my-text-domain'),
            'plural'            => __('Brands', 'my-text-domain'),
            'slug'              => 'brands'
        ),
    

    hope you can help. thnx.

    opened by slobich 5
Releases(v1.4)
Owner
Joe Grainger
Human
Joe Grainger
Wordpress advance plugin with multi purposes features like live chat, custom post type, custom forms, word count etc

What is this? This is wordpress plugin which is created for the multi purpose uses. How to use? Simply install the plugin. Go to the plugin settigs pa

Amir Liaqat 2 Jun 23, 2022
A custom WordPress nav walker class to fully implement the Twitter Bootstrap 4.0+ navigation style (v3-branch available for Bootstrap 3) in a custom theme using the WordPress built in menu manager.

WP Bootstrap Navwalker This code in the main repo branch is undergoing a big shakeup to bring it in line with recent standards and to merge and test t

WP Bootstrap 3.3k Jan 5, 2023
A super simple abstraction to make creating a custom Taxonomies in WordPress a breeze

A super simple abstraction to make creating a custom Taxonomies in WordPress a breeze

Joe Grant 2 Apr 5, 2022
A WordPress package for updating custom plugins and themes based on an API response from a custom update server.

WordPress Update Handler A WordPress package for updating custom plugins and themes based on an JSON REST API response from a custom update server. Ch

WP Forge 7 Oct 5, 2022
Adds a dashboard widget that allows admins to quickly open the edit screen for any WordPress post type- including orders, products, and subscriptions.

Quick Open Dashboard Widget Requires PHP: 7.0 WP requires at least: 5.7 WP tested up to: 5.7 WC requires at least: 5.6.0 WC tested up to: 5.8.0 Stable

Universal Yums 4 Nov 11, 2021
🔍️ A WordPress plugin to automatically send a user to the page or post if it's the only search result available.

One Search Result A WordPress plugin to automatically send a user to the page or post if it's the only search result available. When there is only one

Brad Parbs 9 Oct 6, 2021
Querycase provides a convenient, fluent interface for creating and running database queries in WordPress.

Querycase database for WordPress Dependency-free library to create SQL Queries in WordPress. Explore the documentation → ℹ️ About Querycase Querycase

Alessandro Tesoro 7 Oct 17, 2021
A package that makes creating WordPress settings pages a breeze.

WP Settings This package aims to make it easier to create settings pages for WordPress plugins. Typically, you would use the Settings API or write som

Jeffrey van Rossum 43 Nov 24, 2022
Scaffold plugin for creating and managing Blocks, Block Patterns, Block Styles and Block Editor Sidebars in the WordPress Block Editor (aka Gutenberg).

WordPress Block Editor Scaffold This project is a template repo for developing WordPress Blocks, Block Patterns, Block Styles and Block Editor Sidebar

Rareview 6 Aug 2, 2022
Base classes for creating WordPress shortcodes.

WDS Shortcodes Contributors: WebDevStudios, jtsternberg, JayWood Donate link: http://webdevstudios.com Tags: shortcode button, shortcodes, cmb2, utili

WebDevStudios 26 Jun 19, 2020
Custom WordPress theme for DotOrg

wd_s Debt Collective Theme Table of Contents Introduction Getting Started Prerequisites Quick Start Advanced Setup Development Contributing and Suppor

The Debt Collective 1 Oct 31, 2022
Word Count (Custom WordPress Plugin)

word-count (Custom WordPress Plugin) Followed a tutorial to create a plugin that adds word count infos to the frontend (Posts only). I then modified t

null 1 Feb 4, 2022
Wordless is a junction between a WordPress plugin and a theme boilerplate that dramatically speeds up and enhances your custom theme creation

Wordless is a junction between a WordPress plugin and a theme boilerplate that dramatically speeds up and enhances your custom theme creation. Some of

weLaika 1.4k Dec 9, 2022
A custom update API for WordPress plugins and themes

A custom update API for WordPress plugins and themes. Intended to be used in conjunction with my plugin-update-checker library.

Yahnis Elsts 717 Dec 31, 2022
Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple

Create custom WordPress routes and redirects, restrict access by roles and/or capabilities. Routes made simple

Joan 9 Oct 10, 2022
WordPress core test suite function and class declaration stubs for static analysis by PHPStan

WordPress Core Test Suite Stubs This package provides stub declarations for the WordPress Core Test Suite functions, classes and interfaces. These stu

PHP Stubs Library 5 Dec 14, 2022
WPCloudDeploy is a WordPress plugin that allows you to easily deploy servers at major cloud-server providers and then install apps

WPCloudDeploy is a WordPress plugin that allows you to easily deploy servers at major cloud-server providers and then install apps

WPCloudDeploy 41 Dec 24, 2022
Ormapker is a wordpress plugin to embbed a multilocations map easily.

ORMAPKER Ormapker is a wordpress plugin to embbed a multilocations map easily. License This plugin is released under the GNU General Public License Ve

Said Gamih 1 Aug 10, 2022
A WordPress plugin that demonstrates how to easily add frontend interactivity with Alpinejs.

Add Alpinejs to Custom Gutenberg Blocks Is there a fun/easy/lightweight way to add frontend interactivity to custom Gutenberg blocks w/o using React o

null 9 Apr 20, 2022