With over a decade of web development experience, I specialize in Drupal (7, 8, 9, 10), CodeIgniter, Laravel, and WordPress. I offer extensive expertise in both module and theme development, providing customized solutions for complex projects. Whether you need to enhance an existing platform, create new features, or seek expert guidance, I'm here to assist. My dedication to delivering high-quality, efficient, and scalable solutions is unmatched. Feel free to contact me to explore how I can contribute to your project's success. Let's turn your ideas into reality!

“Learn the essentials of creating WordPress custom post types, unlocking powerful content customization options for a personalized and efficient website.”

WordPress offers a variety of post types to facilitate the organization of your website's content. You can effortlessly create a chronological blog or showcase static pages using these default post types. However, for larger websites with diverse content, the built-in post types might not be sufficient, prompting the need to create your own custom post type.

This article aims to guide you through the process of creating a custom post type in WordPress, providing insights into customization to enhance its functionality.

Understanding WordPress Custom Post Type

A WordPress custom post type is an additional content category that users create to better organize their website's content. This is particularly useful when your website contains diverse content that doesn't fit into WordPress's default post types.

While categories can be assigned to organize content, posts within the same custom post type appear in a unified list, making it easier to track and manage. By default, WordPress has seven post types:

  1. Posts: Regular blog posts.
  2. Pages: Static content not listed by date.
  3. Attachments: All media files, including images, videos, or PDFs.
  4. Revisions: Saved versions of all post types.
  5. Navigation Menus: Links for website navigation.
  6. Custom CSS: Customizable type for modifying WordPress themes.
  7. Changesets: Tracks changes made in the customizer.

WordPress custom post types allow you to categorize content more effectively, grouping it without the need for traditional categories and providing an easy way to track posts within different sections.

Elements of a WordPress Custom Post Type

Before delving into the creation process, it's crucial to understand the terms "array" and "element." In the context of custom post types, an array is a data structure storing key-value pairs known as elements, which define the properties of the custom post type.

Three essential arrays contain different elements to create a custom WordPress post type: $args, $labels, and $supports. The $args array includes key-value pairs such as description, public, menu_position, has_archive, and others, defining various aspects of the post type.

Additionally, the $labels array defines text-related aspects, such as name, singular_name, add_new, and others, while the $supports array contains elements that enable specific features for the custom post type.

Creating a WordPress Custom Post Type

There are three methods to add custom post types in WordPress, each with its pros and cons:

  1. Using a Normal Plugin: Simple but the custom post type may be deleted if the plugin is uninstalled.
  2. Editing the Theme's functions.php File: Doesn't require an additional tool but may lose data after a theme update.
  3. Creating a Site-Specific Plugin: Preserves data and is highly customizable but requires technical skills.

This article demonstrates the third method. To create custom post types, use the register_post_type() function, with the custom post type name and the $args array as parameters. It's essential to hook these functions to the init action hook for proper registration.

The provided example code showcases a custom article post type plugin, emphasizing the use of $labels and $args arrays for customization.

Customizing the New Post Type

After creating a custom post type, customization options are available to differentiate it from other content. Template files, namely single-{post_type}.php and archive-{post_type}.php, can be created in the active theme's directory for this purpose.

To create these template files, duplicate the theme's existing single.php and archive.php files, rename them based on the custom post type (e.g., single-article.php and archive-article.php), and make necessary modifications. This ensures customization without affecting the entire site.

Adding a Meta Box to a Custom Post Type

Meta boxes, editing screen windows for adding post metadata, can enhance content details. Custom meta boxes can be created by editing the theme's functions.php or the site-specific plugin's code. The example code provided demonstrates how to add an Author meta box to a custom article post type.

Ensure proper saving of entered values by including the code snippet to save meta box data. The wp_nonce_field function adds a nonce field to the form for security.

Displaying Custom Post Types on the Front Page

By default, WordPress custom post types are not displayed on the front page. To enable this, a custom function is introduced, utilizing the pre_get_posts action hook. The example code includes a function (add_article_to_frontpage) that modifies the main query to include both default and custom post types on the front page.

Adding and Displaying WordPress Custom Field

Custom fields provide additional details to content. WordPress offers a default custom field tool, but a plugin like Advanced Custom Fields can limit specific custom fields to selected post types.

For default custom fields, activate the hidden tool in the Post Editor, add fields, and display them in the theme using functions like the_meta() or echo get_post_meta().

For Advanced Custom Fields, create custom fields, set location rules for the desired post type, and use the plugin's functions to display the custom fields in the theme.

Conclusion

In conclusion, creating a custom post type in WordPress empowers users to organize content more effectively, especially on larger websites with diverse content. The process involves creating a site-specific plugin, utilizing the register_post_type() function, and customizing template files.

Further customization options, such as adding meta boxes and custom fields, enhance the functionality of custom post types. Displaying custom post types on the front page and incorporating custom fields contribute to a more versatile and organized WordPress website. Understanding these aspects allows users to tailor their websites to specific needs and improve content management.

Here's a full code example for creating a custom post type in WordPress and adding a custom meta box for author details:

<?php
/*
Plugin Name: Custom Post Types
Description: Add post types for custom articles
Author: Hostinger Dev
*/

// Hook ht_custom_post_custom_article() to the init action hook
add_action('init', 'ht_custom_post_custom_article');

// The custom function to register a custom article post type
function ht_custom_post_custom_article() {
    // Set the labels. This variable is used in the $args array
    $labels = array(
        'name'               => __('Custom Articles'),
        'singular_name'      => __('Custom Article'),
        'add_new'            => __('Add New Custom Article'),
        'add_new_item'       => __('Add New Custom Article'),
        'edit_item'          => __('Edit Custom Article'),
        'new_item'           => __('New Custom Article'),
        'all_items'          => __('All Custom Articles'),
        'view_item'          => __('View Custom Article'),
        'search_items'       => __('Search Custom Article'),
        'featured_image'     => 'Poster',
        'set_featured_image' => 'Add Poster'
    );

    // The arguments for our post type, to be entered as parameter 2 of register_post_type()
    $args = array(
        'labels'            => $labels,
        'description'       => 'Holds our custom article post specific data',
        'public'            => true,
        'menu_position'     => 5,
        'supports'          => array('title', 'editor', 'thumbnail', 'excerpt', 'comments', 'custom-fields'),
        'has_archive'       => true,
        'show_in_admin_bar' => true,
        'show_in_nav_menus' => true,
        'query_var'         => true,
    );

    // Call the actual WordPress function
    // Parameter 1 is a name for the post type
    // Parameter 2 is the $args array
    register_post_type('article', $args);
}

// Add meta box
add_action('add_meta_boxes', 'add_author_meta_box');

function add_author_meta_box() {
    add_meta_box(
        "author_meta_box",     // Meta box ID
        "Author Details",       // Meta box title
        "author_meta_box_callback", // Meta box callback function
        "article",             // The custom post type parameter 1
        "side",                // Meta box location in the edit screen
        "high"                 // Meta box priority
    );
}

function author_meta_box_callback() {
    wp_nonce_field('author-nonce', 'meta-box-nonce');
    global $post;
    ?>
    <th><label for="author_name_field">Author Name</label></th>
    <td><input type="text" id="author_name" class="regular-text" name="Author_Name" value="<?php echo get_post_meta($post->ID, 'Author_Name', true); ?>" /></td>

    <th><label for="author_id_field">Author ID</label></th>
    <td><input type="text" id="author_id" class="regular-text" name="Author_ID" value="<?php echo get_post_meta($post->ID, 'Author_ID', true); ?>" /></td>
    <?php
}

// Save meta box data
add_action('save_post', 'author_save_postdata');

function author_save_postdata($post_id) {
    // If this is an autosave, our form has not been submitted
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;

    // Retrieve post id
    if ('article' !== get_post_type()) {
        return $post_id;
    }

    // Check the user's permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
    } else {
        if (!current_user_can('edit_post', $post_id))
            return $post_id;
    }

    // Sanitize user input.
    $author_name = sanitize_text_field($_POST['Author_Name']);
    $author_id = sanitize_text_field($_POST['Author_ID']);

    // Update the meta fields in the database.
    update_post_meta($post_id, 'Author_Name', $author_name);
    update_post_meta($post_id, 'Author_ID', $author_id);
}

This code creates a custom post type called "article" with an associated meta box for Author Details. The Author Details meta box includes fields for Author Name and Author ID. The data entered into these fields is then saved as custom post meta.

Remember to save this code in a file named custom-post-type.php and follow the instructions mentioned in the original article for creating a plugin and activating it in WordPress.

Posted by Sujan Shrestha
Categorized:
PREVIOUS POST
banner