Creating a custom post type (CPT) in WordPress allows you to organize and display content beyond the default posts and pages. When combined with the Advanced Custom Fields (ACF) plugin, you can add custom fields to tailor your content even further. This guide walks you through the process of creating a CPT with ACF.
Step 1: Register Your Custom Post Type
Begin by adding code to your theme's functions.php file or a custom plugin. Use the register_post_type function to define your CPT. Here's an example for creating a "Portfolio" post type:
function create_portfolio_cpt() {
$args = array(
'public' => true,
'label' => 'Portfolios',
'supports' => array('title', 'editor', 'thumbnail'),
'has_archive' => true,
'show_in_rest' => true,
);
register_post_type('portfolio', $args);
}
add_action('init', 'create_portfolio_cpt');
This code registers a new post type called "Portfolio" that supports titles, editors, and thumbnails. It also enables REST API support for Gutenberg compatibility.
Step 2: Install and Activate Advanced Custom Fields
Download and install the Advanced Custom Fields plugin from the WordPress plugin repository. Activate the plugin to start creating custom fields.
Step 3: Create Custom Fields for Your CPT
Navigate to Custom Fields > Add New in the WordPress admin menu. Create a new field group, and assign it to your CPT by setting the location rules to Post Type is equal to Portfolio.
- Enter a field label, e.g., "Project Year".
- Select the field type, such as "Number" or "Text".
- Configure any additional options as needed.
Publish the field group to save your custom fields.
Step 4: Display Custom Fields in Your Theme
To show the custom fields on your CPT archive or single pages, edit your theme files. Use the get_field function provided by ACF. For example, in single-portfolio.php:
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<div>Project Year: <?php echo get_field('project_year'); ?></div>
<div>Content: <?php the_content(); ?></div>
<?php endwhile; endif; ?>
This code retrieves and displays the custom field "Project Year" along with the post content.
Conclusion
By following these steps, you can create a custom post type tailored to your needs and enhance it with custom fields using ACF. This setup allows for flexible content management and presentation on your WordPress site.