WordPress custom post guide
Custom post type is a post where we can define custom post as we need. Using Custom post type we can add or modify functionality with existing one. We learn about how to create custom post step by step below.
Step 1: Define your custom post type
To define your custom post type, you need to use the register_post_type()
function. Here’s an example of how to create a custom post type for a myposttype:
function create_my_post_type() {
$args = array(
'labels' => array(
'name' => __( 'My Post type' ),
'singular_name' => __( 'My Post Type' ),
),
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'myposttype' ),
'menu_icon' => 'dashicons-portfolio',
'supports' => array( 'title', 'editor', 'thumbnail' ),
);
register_post_type( 'myposttype', $args );
}
add_action( 'init', 'create_my_post_type' );
Step 2: Create custom meta boxes
If you want to add custom fields to your custom post type, you can use the add_meta_box()
function. Here’s an example of how to create a meta box for a myposttype:
function add_myposttype_metaboxes() {
add_meta_box(
'myposttype_meta',
'Myposttype Details',
'myposttype_meta_callback',
'myposttype',
'normal',
'default'
);
}
add_action( 'add_meta_boxes', 'add_myposttype_metaboxes' );
function myposttype_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'myposttype_nonce' );
$portfolio_meta = get_post_meta( $post->ID );
?>
<label for="myposttype_year"><?php _e( 'Year' ); ?></label>
<input type="text" name="myposttype_year" id="myposttype_year" value="<?php if ( isset ( $myposttype_meta['myposttype_year'] ) ) echo $myposttype_meta['myposttype_year'][0]; ?>" />
<?php
}
Step 3: Save custom meta box data
To save the custom meta box data, you need to use the save_post
hook. Here’s an example of how to save the myposttype year meta box data:
function save_myposttype_meta( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST['myposttype_nonce'] ) && wp_verify_nonce( $_POST['myposttype_nonce'], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST['myposttype_year'] ) ) {
update_post_meta( $post_id, 'myposttype_year', sanitize_text_field( $_POST['myposttype_year'] ) );
}
}
add_action( 'save_post', 'save_myposttype_meta' );
Step 4: Display custom post type on the front-end
To display your custom post type on the front-end of your site, you need to use a custom query. Here’s an example of how to display a list of myposttype items:
$args = array(
'post_type' => 'myposttype',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts()): the_post();
echo '<h1'>'.the_title().''</h1>';
echo '<p>''.the_content().''</p>';
endwhile; endif;