Custom Post Types and Taxonomies

Summary: Learning about Custom Post Types, Taxonomies, Custom Taxonomies, Utility or Shadow Taxonomies.

Custom Post Types

WordPress comes with five default post types: postpageattachmentrevision, and menu.

While developing your plugin, we may need to create your own specific content type like products for an e-commerce website, assignments for an e-learning website, or movies for a review website.

To register a custom post type we can use the register_post_type() function, which should be called within the init action hook.

function create_movie_post_type() {
    $labels = array(
        'name'               => _x('Movies', 'post type general name'),
        'singular_name'      => _x('Movie', 'post type singular name'),
        'menu_name'          => _x('Movies', 'admin menu'),
        'name_admin_bar'     => _x('Movie', 'add new on admin bar'),
        'add_new'            => _x('Add New', 'movie'),
        'add_new_item'       => __('Add New Movie'),
        'new_item'           => __('New Movie'),
        'edit_item'          => __('Edit Movie'),
        'view_item'          => __('View Movie'),
        'all_items'          => __('All Movies'),
        'search_items'       => __('Search Movies'),
        'parent_item_colon'  => __('Parent Movies:'),
        'not_found'          => __('No movies found.'),
        'not_found_in_trash' => __('No movies found in Trash.')
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'movies'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array('title', 'editor', 'excerpt', 'thumbnail', 'comments'),
        'show_in_rest'       => true,
    );

    register_post_type('movie', $args);
}

add_action('init', 'create_movie_post_type');

Querying by Post Type

Querying by post type in WordPress allows us to retrieve specific types of content programmatically, such as custom post types you’ve registered. WordPress provides several methods to query posts by post type, including using the WP_Query class, get_posts(), or even custom SQL queries if needed.

$args = array(
    'post_type' => 'book', // Specify the custom post type
    'posts_per_page' => 10, // Number of posts to retrieve
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Output post content or title, etc.
        the_title('<h2>', '</h2>');
        the_excerpt();
    }
    wp_reset_postdata(); // Reset post data
} else {
    echo 'No books found';
}
  • post_type: The post type slug we want to query. This can be a custom post type or any of the built-in types like post or page.
  • posts_per_page: The number of posts to retrieve. We can set this to -1 to retrieve all posts.
  • wp_reset_postdata(): It’s important to reset the global post data after running a custom loop to ensure that subsequent queries and template tags function correctly.

Taxonomies

Taxonomies in WordPress are a powerful way to classify and organize content. They are used to group posts together based on shared attributes, making it easier for users to find related content. WordPress comes with two built-in taxonomies like categories and tags.

Categories: A hierarchical taxonomy used to organize posts into broad groups. Categories can have parent and child terms, creating a tree structure.

Tags: A non-hierarchical taxonomy used to describe specific details about posts. Tags do not have a parent-child relationship.

Registering a Custom Taxonomy

To register a custom taxonomy, we can use the register_taxonomy() function. This function is called within the init action hook.

function create_custom_taxonomy() {
    $labels = array(
        'name'              => _x('Genres', 'taxonomy general name'),
        'singular_name'     => _x('Genre', 'taxonomy singular name'),
        '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, // Set to true for hierarchical taxonomies (like categories)
        '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_custom_taxonomy');

  • Taxonomy Key ('genre'): The first argument in register_taxonomy() is the taxonomy key (slug). This is the unique identifier for the taxonomy and should be lowercase, with no spaces, and less than 32 characters.
  • Object Types (array('book')): The second argument is an array of object types to which the taxonomy is applied. This could be one or more post types (e.g., 'post', 'page', 'book').
  • Arguments Array ($args): The third argument is an array of options that define the taxonomy’s behavior and labels.
  • rewrite: An array to customize the permalink structure for the taxonomy. The 'slug' key allows you to define the URL slug.
  • hierarchical: Determines if the taxonomy is hierarchical like categories (true) or flat like tags (false).
  • labels: An array of labels used in the WordPress admin. Important labels are
    • name: The plural name of the taxonomy.
    • singular_name: The singular name of the taxonomy.
    • search_items: The text for the search box.
    • all_items: The text to display all taxonomy terms.
    • parent_item: The text for the parent item (for hierarchical taxonomies).
    • edit_item: The text for the “Edit” link.
    • add_new_item: The text for the “Add New” link.
  • show_ui: A boolean that determines whether a user interface for managing the taxonomy should be available in the WordPress admin.
  • show_admin_column: A boolean that adds the taxonomy as a column on the post listing page in the admin area.
  • query_var: A boolean that determines whether the taxonomy should have a query variable. If set to true, you can query the taxonomy using its slug in the URL (e.g., ?genre=fiction).

Utility Taxonomies or Shadow Taxonomies

Utility taxonomies, sometimes referred to as shadow taxonomies, are custom taxonomies in WordPress that serve a specific purpose behind the scenes. Unlike traditional taxonomies like categories and tags, utility taxonomies are often not directly exposed to users but are instead used for internal organization, filtering, or managing content in more advanced ways.

Content Organization: Categorize or tag posts, pages, or custom post types for internal purposes without exposing these classifications to the front end. For example we might create a utility taxonomy to flag posts for a specific campaign or workflow.

Query Optimization: Use utility taxonomies to improve the efficiency of queries by grouping content that shares certain characteristics. This is particularly useful in complex WordPress sites with large amounts of content.

Conditional Logic: Use utility taxonomies in conjunction with custom fields or other plugins to apply conditional logic to content. For example we might display or hide certain content sections based on the presence of a specific taxonomy term.

function register_utility_taxonomy() {
    $labels = array(
        'name'                       => _x('Internal Tags', 'taxonomy general name'),
        'singular_name'              => _x('Internal Tag', 'taxonomy singular name'),
        'search_items'               => __('Search Internal Tags'),
        'all_items'                  => __('All Internal Tags'),
        'edit_item'                  => __('Edit Internal Tag'),
        'update_item'                => __('Update Internal Tag'),
        'add_new_item'               => __('Add New Internal Tag'),
        'new_item_name'              => __('New Internal Tag Name'),
        'menu_name'                  => __('Internal Tags'),
    );

    $args = array(
        'hierarchical'          => false, // Set to false for non-hierarchical taxonomy like tags
        'labels'                => $labels,
        'public'                => false, // Hide from public view
        'show_ui'               => true,  // Show in the admin area
        'show_admin_column'     => true,  // Show as a column in post listing screen
        'query_var'             => false, // Disable query var
        'rewrite'               => false, // Disable rewriting of URLs
    );

    register_taxonomy('internal_tag', 'post', $args);
}

add_action('init', 'register_utility_taxonomy');

«
»

Leave a Reply

Your email address will not be published. Required fields are marked *