7.1. WordPress Custom Post Type

With Share on Social Plugin, admins can create and configure multiple Social Lockers. While it is not impossible to use WordPress option to store locker settings, better approach would be to use WordPress Custom Post Type which provides much more robust and convenient framework to manage multiple items of a type.

In this chapter, we explain how to add new WordPress Custom Post Type and manage custom posts and its meta data.

WordPress Custom Post Type

In WordPress, entities like Posts, Pages and Attachments are different versions of base type Posts. They all holds some contents and also, other attributes or values called as meta data. WordPress allows developers to add custom post types which enables them extend the functionality of the base post type.

For each Social Locker we need to save additional settings such as id, share link, enabled social networks and display text. As WordPress Custom Post Type allows creation of multiple items of a custom post type and save meta data with each item, it is well suited for Social Lockers.

WordPress custom post type integrates seamlessly with WordPress core. Each custom Post Type, just like Post and Pages, gets its own menu in Admin Menu and inherits WordPress Post management framework to list, add, delete, publish and edit items or entities.

In Share on Social Plugin, we add new custom post type - sos - and extend it further to use it as Sos Lockers. The sos custom post type adds a new menu item Share on Social to admin menu.

wp-pd-sos-custom-post-menu](../media/wp-pd-sos-custom-post-menu-300x159.png)

In Share on Social menu, WordPress by default adds first two sub menu items - Lockers and Add New - as part of its core post management framework. The last two items - Settings and Statistics - which are added by the plugin just to group them under the menu and they are not related to custom post.

Class file admin/class-sos.php handles the sos custom post type. In the setup() method, we add create_post_type() method as action method to action hook init.

share-on-social/admin/class-sos.php

class Sos {

    var $post_type = 'sos';

    public function setup () {

        add_action( 'init',array($this,'create_post_type' ) );
    ....

In action method, we use WordPress API function [register_post_type() to register new custom type.

share-on-social/admin/class-sos.php

public function create_post_type () {

    register_post_type( $this->post_type, 
        array(
            'labels' => array(
                'name' => _x( 'Sos Lockers', 'post type general name', 'sos-domain' ),
                'singular_name' => _x( 'Sos Locker', 'post type singular name', 
                                       'sos-domain' ),
                'menu_name' => _x( 'Share on Social', 'admin menu', 'sos-domain' ),
                'add_new' => _x( 'Add New', 'sos', 'sos-domain' ),
                'add_new_item' => __( 'Add New Locker', 'sos-domain' ),
                'edit' => __( 'Edit', 'sos-domain' ),
                'edit_item' => __( 'Edit Locker', 'sos-domain' ),
                'new_item' => __( 'New Locker', 'sos-domain' ),
                'all_items' => __( 'Lockers', 'sos-domain' ),
                'view' => '',
                'view_item' => ''
            ),  
                        
            'public' => false,
            'show_ui' => true,
            'menu_position' => 15, 
            'supports' => array('title'),
            'taxonomies' => array(''),
            'menu_icon' => SOS_URL . '/images/sos-icon.png',
            'has_archive' => true,
            'register_meta_box_cb' => array($this,'setup_meta_boxes')
        ) );

    if ( null == Sos_Helper::get_locker_post_id( 'basic' ) ) { 
        $this->create_basic_locker();
    }   

}

The first parameter is custom post type name which is set to sos. The second parameter is an array of arguments. The function defines a large number of arguments and we use only some of them. Refer the register_post_type() for the complete list of parameters and arguments.

The first arg is an array which holds the various labels used by the post type. Other important args are

  • public - set it as false so that only admin can manage sos custom post type (add new, delete etc.,).

  • show_ui - display a user-interface (admin panel) for this post type.

  • supports - WordPress post editor, by default, allows title field and content editor. Using arg, supports, we can enable or disable other fields like thumbnails, excerpts etc., Custom post type sos allows only the title field.

With this, sos post editor has a single field to enter title of the post. Other fields of Sos Lockers such as Locker ID, Share on, Share URL and Display Text have to be stored as meta data of the post. To input meta data, we need meta boxes in post editor and for this use argument register_meta_box_cb to register callback function that setup meta boxes in the edit form. We cover meta box callback function in next blog.

 
 

All-in-one function, register_post_type(), accomplishes many things.

  • registers the sos custom post type.

  • sets labels for add new item, edit item, custom post admin menu and view items etc.,

  • enables admin panel to manage custom post items - Sos Lockers.

  • enable or disable fields in post editor.

  • provides callback to customize meta boxes in post editor.

Custom Post Type Scope

Don’t assume that custom type registration is one time affair in WordPress.

Instead, whenever we access admin screen or any of its menu, as part of request cycle, init hook executes register_post_type(). In other words, during each request, WordPress freshly registers custom post type and discards it once request is completed!

After registering the sos custom post type, we add a new post of sos type which is the default locker with locker id basic. While adding the default locker, we check whether locker with same id exists and create only if it not found in database. This check is essential otherwise each request adds a new locker.

share-on-social/admin/class-sos.php

    public function create_basic_locker () {
        if ( false == current_user_can( 'activate_plugins' ) ) {
            return;
        }

        $post = array(
                'post_name' => 'basic',
                'post_title' => 'Basic Locker',
                'post_status' => 'publish',
                'post_type' => 'sos' );
        $post_id = wp_insert_post( $post );

        if ( $post_id != 0 ) {
            add_post_meta( $post_id, 'locker_id', 'basic' );
            add_post_meta( $post_id, 'shareon_fb', '1' );
            add_post_meta( $post_id, 'shareon_gplus', '1' );
            add_post_meta( $post_id, 'shareon_twitter', '1' );
            add_post_meta( $post_id, 'share_target', 'page' );
            add_post_meta( $post_id, 'locker_text', $this->basic_text() );
        }
    }

While inserting the post, check whether user has the required capability - activate-plugins. We set, among other things, post_type as sos in $post array. WordPress function wp_insert_post() inserts the post to wp_posts table. This table holds posts of all types - posts, pages and even custom posts. On success, function returns the post id of new post. We use the post id to add meta data for Basic Locker such as

  • locker_id - basic

  • shareon_fb, shareon_gplus and shareon_twitter - enable all Share Buttons in Basic Locker.

  • share_target - Basic Locker shares URL of the page where locker is placed.

  • locker_text - HTML snippet that is used as locker display text.

Sos Lockers listing shows default locker - Basic. However, if we try to add new one or edit the basic locker, the editor shows only the Title field as we are yet to add meta boxes.

In the next section, we show how to add meta boxes to the post editor to manage post meta data.