When you instill WordPress, You will only see three default built-in content types on the website admin panel, like posts, pages, and media. You will think, this is not enough for your website. So, You will depend on the third-party plugins. A plugin can your website super slow. However, Today WordPress has become malleable and advanced. You can make your website more attractive and you can add more content, images using WordPress Custom Post Types functions. Also, you can create as many Custom Post Types as you want. In this context, I will show you how to create custom post types in WordPress and I will also show you how to display custom post types in your website front-end.

What is Custom Post Type in WordPress?

Very simple question, WordPress Custom Post Types are content types e.g posts and pages. According to Codex, Custom Post Types are also known as Custom Content Types that can add to your WordPress website using a function called the register_post_type(). Here, By default, WordPress post types:

  • Post
  • Page
  • Attachment
  • Revision
  • Navigation Menu

You may need to create Custom Post Types e.g, Portfolio, Testimonials, Products, etc.

Create a WordPress Custom Post Type

First, I would like to show with you a quick fully Custom Post Types working example that you interpret how it works. I will use WordPress action hook add_action( ‘init’, ‘custom_post_type’ ), custom_post_type() your function name. Learn more here WordPress init Hook Developer Resources

// custom post type function
function custom_post_type() {
    // post type movies, so you can add anything
    register_post_type( 'movies',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'Movies' ),
                'singular_name' => __( 'Movie' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'movies'),
        )
    );
}
// Hooking up function to theme setup
add_action( 'init', 'custom_post_type' );

I have created movies post type with an array of arguments. So, You can create a post type e.g news, portfolio, etc. And last part contains other arguments like public visibility, has archive, and slug that will be used in URLs for this post type. Now, let’s create a custom post type for your WordPress Theme. Add the following piece of code in your active theme function.php file below.

/*
* Creating a function to create post type 
*/
 
function custom_post_type() {
 
// Set UI labels for Custom Post Type
    $labels = array(
        'name'                => _x( 'Movies', 'Post Type General Name', 'text-domain' ),
        'singular_name'       => _x( 'Movie', 'Post Type Singular Name', 'text-domain' ),
        'menu_name'           => __( 'Movies', 'text-domain' ),
        'parent_item_colon'   => __( 'Parent Movie', 'text-domain' ),
        'all_items'           => __( 'All Movies', 'text-domain' ),
        'view_item'           => __( 'View Movie', 'text-domain' ),
        'add_new_item'        => __( 'Add New Movie', 'text-domain' ),
        'add_new'             => __( 'Add New', 'text-domain' ),
        'edit_item'           => __( 'Edit Movie', 'text-domain' ),
        'update_item'         => __( 'Update Movie', 'text-domain' ),
        'search_items'        => __( 'Search Movie', 'text-domain' ),
        'not_found'           => __( 'Not Found', 'text-domain' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'text-domain' ),
    );
     
// Set other options for Custom Post Type
     
    $args = array(
        'label'               => __( 'movies', 'text-domain' ),
        'description'         => __( 'Movie news and reviews', 'text-domain' ),
        'labels'              => $labels,
        // Features this CPT supports in Post Editor
        'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
        // You can associate this CPT with a taxonomy or custom taxonomy. 
        'taxonomies'          => array( 'genres' ),
        /* A hierarchical CPT is like Pages and can have
        * Parent and child items. A non-hierarchical CPT
        * is like Posts.
        */ 
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'menu_position'       => 5,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'page',
    );
     
    // Registering your Custom Post Type
    register_post_type( 'movies', $args );
 
}
 
/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/
 
add_action( 'init', 'custom_post_type', 0 );


After adding this code you will see your dashboard Movies menu in the left sidebar under the post menu. Like the following attached.

Create A WordPress Custom Post Type

Displaying Custom Post Types on The Front Page

Display Custom Post Types on the website. If you would like them to display among your regular post, then add this code in your functions.php file.

 
function display_post_types_to_query( $query ) {
    if ( is_home() && $query->is_main_query() )
        $query->set( 'post_type', array( 'post', 'movies' ) );
    return $query;
}
add_action( 'pre_get_posts', 'display_post_types_to_query' );

Querying Custom Post Types

If you are recognizable with the coding and if you would like to run loop queries in your templates, then this code will help you.

 
<?php 
$args = array( 'post_type' => 'movies', 'posts_per_page' => 10 );
$the_query = new WP_Query( $args ); 
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<div class="entry-content">
<?php the_content(); ?> 
</div>
<?php wp_reset_postdata(); ?>
<?php else:  ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Custom Taxonomies for Custom Post Types

If you would like to learn, What is a Taxonomy? or How To Create Custom Taxonomies In WordPress, then please check this article. Because of this tutorial, I wouldn’t mention again the detailed WordPress Taxonomy. However, In this context, I would like to show with you, Create Custom Taxonomies for the WordPress Custom Post Types. So, Let’s start,

function taxonomies_movies() {
  $labels = array(
    'name'              => _x( 'Movies Categories', 'taxonomy general name' ),
    'singular_name'     => _x( 'Movies Category', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Movie Categories' ),
    'all_items'         => __( 'All Movie Categories' ),
    'parent_item'       => __( 'Parent Movie Category' ),
    'parent_item_colon' => __( 'Parent Movie Category:' ),
    'edit_item'         => __( 'Edit Movie Category' ), 
    'update_item'       => __( 'Update Movie Category' ),
    'add_new_item'      => __( 'Add New Movie Category' ),
    'new_item_name'     => __( 'New Movie Category' ),
    'menu_name'         => __( 'Movie Categories' ),
  );
  $args = array(
    'labels' => $labels,
    'hierarchical' => true,
  );
  register_taxonomy( 'movies_category', 'movies', $args );
}
add_action( 'init', 'taxonomies_movies', 0 );

After adding this code, You will see in your website admin dashboard, that a new dropdown menu tab, looks like the following attached.

Custom Taxonomies For Custom Post Types

So, now you can add the category for your Custom Post Types.

Add Post Meta Boxes

If you would like to sell your products online, you may need to add products price and descriptions. So, You can add very easy these fields using the WordPress Meta box. So, I will help you in creating a custom meta box for WordPress Custom Post Types.

  • Step 1: Create a Meta Box

Add the following code in your active theme functions.php file.

add_action( 'add_meta_boxes', 'movies_price_box' );
function movies_price_box() {
    add_meta_box( 
        'product_price_box',
        __( 'Movie Price', 'theme_textdomain' ),
        'product_price_box_content',
        'movies',
        'side',
        'high'
    );
}

Add Post Meta Boxes
The above code creates the meta box with the following parameters:

  • The Meta box Title visible for the users (A title should be unique).
  • The function will display the contents of the meta box.
  • The post type the meta box belongs to.
  • The priority of the meta box (how “high” and “side” it is displayed).
  • Step 2: Add a Field

Add the following code in your active theme functions.php file.


function product_price_box_content( $post ) {
  wp_nonce_field( plugin_basename( __FILE__ ), 'product_price_box_content_nonce' );
  echo '<label for="product_price"></label>';
  echo '<input type="text" id="product_price" name="product_price" placeholder="enter a movie price" />';
}


 Add a Field

  • Step 3: Save Data

Add the following code in your active theme functions.php file.

add_action( 'save_post', 'movie_price_box_save' );
function movie_price_box_save( $post_id ) {

  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
  return;

  if ( !wp_verify_nonce( $_POST['product_price_box_content_nonce'], plugin_basename( __FILE__ ) ) )
  return;

  if ( 'page' == $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_page', $post_id ) )
    return;
  } else {
    if ( !current_user_can( 'edit_post', $post_id ) )
    return;
  }
  $product_price = $_POST['product_price'];
  update_post_meta( $post_id, 'product_price', $product_price );
}

A Simple post meta box creating is done. So, you should display this box on your website. Also, you can display it anywhere. Now, I am going to show you, how to display a custom meta box in the WordPress Website. Meta-data can be display easily using the WordPress get_post_meta() function.

<?php
  // If in a loop you can get the post ID easily
  $price = get_post_meta( get_the_ID(), 'product_price', true );

  // To get the price of a random product you will need to know the ID
  $price = get_post_meta( $product_id, 'product_price', true );
?>

In this article, you have learned, Create Custom post types, Custom Taxonomies For Custom Post Types and how to add Post Meta Boxes in the WordPress Website. So, if you have any questions, please comment below.

If you need to create a WordPress Website or WooCommerce website, Fix WordPress Website issues or Speed Up WordPress and WooCommerce website then, please check my Fiverr. To Check: Create an eCommerce Website With WooCommere Or Customize WordPress Website

Conclusion

I think WordPress Custom Post Types is the most important for any WordPress user. You can manage your website using the meta box or post type Or you can write your own plugin using the WordPress register_post_type() function. Really If you enjoyed this article, please share it.

Topics