Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tutorial : Mastering Custom Post Types and Taxonomies in WordPress #3050

Open
sumitsinghwp opened this issue Dec 3, 2024 · 3 comments
Open
Assignees
Labels
[Content] Experienced Author Content development issue where the content creator is an experienced author. [Content] Needs SME Content development issues requiring a Subject Matter Expert to vet the topic.

Comments

@sumitsinghwp
Copy link

Details

  • Content type (Online Workshop, Lesson, Course, Tutorial, or Lesson Plan): Tutorial
  • Content title: Mastering Custom Post Types and Taxonomies in WordPress
  • Topic description: Custom Post Types and Taxonomies in WordPress, crafted for beginners. I'll break it into steps, provide instructions for each, and sample code and placeholder suggestions for screenshots.
  • Audience (User, Developer, Designer, Contributor, etc.): Developer
  • Experience Level (Beginner, Intermediate, Advanced, Any): Any

Learning Objectives

With this tutorial, you’ve created a custom post type, added hierarchical and non-hierarchical taxonomies, and displayed the data on your site. This setup is perfect for creating tailored content structures in WordPress.

Related Resources and Other Notes

Automation Code

Introduction

WordPress allows users to create custom post types (CPTs) and taxonomies to organize and display content beyond standard posts and pages. In this tutorial, you'll learn to:

  1. Register a Custom Post Type (CPT).
  2. Add custom taxonomies (hierarchical and non-hierarchical).
  3. Display custom post type data on your site.

Step 1: Understanding Custom Post Types
WordPress includes default post types such as Posts, Pages, and Attachments. However, for more complex websites, such as a recipe blog or a portfolio, you may need custom types like "Recipes" or "Projects."

Step 2: Registering a Custom Post Type
Custom Post Types are registered using the register_post_type() function. Let's create a CPT called "Books."

Code Example:
Add this code to your theme's functions.php file or a custom plugin:

function create_books_cpt() {
    $labels = array(
        'name'               => 'Books',
        'singular_name'      => 'Book',
        'menu_name'          => 'Books',
        'name_admin_bar'     => 'Book',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Book',
        'edit_item'          => 'Edit Book',
        'new_item'           => 'New Book',
        'view_item'          => 'View Book',
        'all_items'          => 'All Books',
        'search_items'       => 'Search Books',
        'not_found'          => 'No books found.',
        'not_found_in_trash' => 'No books found in Trash.',
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'has_archive'        => true,
        'rewrite'            => array('slug' => 'books'),
        'supports'           => array('title', 'editor', 'thumbnail'),
        'menu_icon'          => 'dashicons-book', // Add a relevant Dashicon
    );

    register_post_type('book', $args);
}
add_action('init', 'create_books_cpt');

What This Code Does:

  • Creates a "Books" post type.
  • Adds it to the WordPress admin menu with a custom icon.
  • Supports Title, Editor, and Thumbnail features.

Screenshot:
Image

Step 3: Adding a Hierarchical Taxonomy (Categories)
Now, let’s add a taxonomy called "Genres" to categorize books. This will behave like "Categories" for posts.

Code Example:
Add this code to functions.php:

function create_genres_taxonomy() {
    $labels = array(
        'name'              => 'Genres',
        'singular_name'     => 'Genre',
        'search_items'      => 'Search Genres',
        'all_items'         => 'All Genres',
        'parent_item'       => 'Parent Genre',
        'parent_item_colon' => 'Parent Genre:',
        'edit_item'         => 'Edit Genre',
        'update_item'       => 'Update Genre',
        'add_new_item'      => 'Add New Genre',
        'new_item_name'     => 'New Genre Name',
        'menu_name'         => 'Genres',
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'genre'),
    );

    register_taxonomy('genre', array('book'), $args);
}
add_action('init', 'create_genres_taxonomy');

What This Code Does:

  • Creates a hierarchical taxonomy called "Genres."
  • Associates it with the "Books" CPT.

Screenshot:
Image

Step 4: Adding a Non-Hierarchical Taxonomy (Tags)
Let’s add another taxonomy called "Authors," which will work like tags.

Code Example:

function create_authors_taxonomy() {
    $labels = array(
        'name'              => 'Authors',
        'singular_name'     => 'Author',
        'search_items'      => 'Search Authors',
        'all_items'         => 'All Authors',
        'edit_item'         => 'Edit Author',
        'update_item'       => 'Update Author',
        'add_new_item'      => 'Add New Author',
        'new_item_name'     => 'New Author Name',
        'menu_name'         => 'Authors',
    );

    $args = array(
        'hierarchical'      => false,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'author'),
    );

    register_taxonomy('author', 'book', $args);
}
add_action('init', 'create_authors_taxonomy');

What This Code Does:

  • Creates a non-hierarchical taxonomy called "Authors."
  • Associates it with the "Books" CPT.

Step 5: Displaying CPT Data on Your Site
To display "Books" on the front end, create a custom template file.

Example: Archive Template for Books
Save this file as archive-book.php in your theme folder:

<?php get_header(); ?>

<h1>Books Archive</h1>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div>
        <h2><?php the_title(); ?></h2>
        <div><?php the_content(); ?></div>
        <p>Genres: <?php the_terms(get_the_ID(), 'genre', '', ', '); ?></p>
        <p>Authors: <?php the_terms(get_the_ID(), 'author', '', ', '); ?></p>
    </div>
<?php endwhile; endif; ?>

<?php get_footer(); ?>

Step 6: Testing and Verifying

  1. Navigate to Books > Add New in the WordPress admin.
  2. Add a few books, assigning genres and authors.
  3. Visit /books/ on your site to view the archive page.
@sumitsinghwp sumitsinghwp added [Content] Experienced Author Content development issue where the content creator is an experienced author. Awaiting Triage Issues awaiting triage. See Training Team handbook for how to triage issues. [Content] Needs SME Content development issues requiring a Subject Matter Expert to vet the topic. and removed Awaiting Triage Issues awaiting triage. See Training Team handbook for how to triage issues. labels Dec 3, 2024
@ironnysh
Copy link

ironnysh commented Dec 3, 2024

Hi team, have you considered presenting alternative, block-based methods to custom post types and taxonomies?

@kaitohm
Copy link
Contributor

kaitohm commented Dec 11, 2024

@sumitsinghwp The team is no longer making Tutorials. Could you make this as a Lesson instead? Please modify the issue title and description. You can then follow https://make.wordpress.org/training/handbook/lessons/lesson-creation-process/ .

I've updated the GitHub issue template so that Tutorials are no longer shown as an option.

@github-project-automation github-project-automation bot moved this to 👋 Ready to Create in LearnWP Content - Development Dec 11, 2024
@kaitohm kaitohm moved this from 👋 Ready to Create to 🚧 Drafts in Progress in LearnWP Content - Development Dec 11, 2024
@sumitsinghwp
Copy link
Author

Thank you @kaitohm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Content] Experienced Author Content development issue where the content creator is an experienced author. [Content] Needs SME Content development issues requiring a Subject Matter Expert to vet the topic.
Projects
Status: 🚧 Drafts in Progress
Development

No branches or pull requests

3 participants