DEV Community

Cover image for WP Custom Post Types
Simon Lee
Simon Lee

Posted on

WP Custom Post Types

While non-coders typically create custom post types in WordPress with a popular plugin called "Custom post types", developers who want to write the code to give your users the ability to create custom post types can use this quick guide to get started.

You could create an action in your functions.php file, but if your content writers, editors were to switch the theme, then that custom post type would no longer be available in the WP Admin. Similarly, you could create a small plugin, but that could also be deactivated by mistake by editors in the WP Admin.

Best practice would be to register your custom post types in a folder called "mu-plugins", which live in their own dedicated folder, and are automatically activated. If you switch themes, your custom post types are still available. Also, they cannot be deactivated from the WP Admin.

Step 1 Register Custom Post Types

Create a folder called "mu-plugins". It should sit alongside your project's "plugins", "themes", "upgrade", etc directories. Then add a new file called (e.g.) "my-custom-post-types.php". Copy & paste the following code to that file.

<?php

function my_custom_post_types() {
  register_post_type('event', array(
    'public' => true,
    'rewrite' => array('slug' => 'events'),
    'has_archive' => true,
    'show_in_rest' => true, # switches from Classic Editor to Block Editor
    'labels' => array(
      'name' => 'Events',
      'add_new_item' => 'Add New Event',
      'edit_item' => 'Edit Event',
      'all_items' => 'All Events',
      'singular_name' => 'Event'
    ),
    'menu_icon' => 'dashicons-hammer'
  ));
}
add_action('init', 'my_custom_post_types');
Enter fullscreen mode Exit fullscreen mode

Visit the WordPress docs to see a list of all the parameters that can be used with register_post_type().

Step 2 Displaying Custom Post Types

You'll have to create a custom query to display custom post types in (for example) front-page.php.

<?php
$latestEvents = new WP_Query(array(
  'posts_per_page' => 2,
  'post_type' => 'event'
));

while($latestEvents -> have_posts()) {
  $latestEvents->the_post(); ?>

  <h2 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
  <div><?php the_content(); ?></div>

<?php } wp_reset_postdata();
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay