How to Create Custom Post Types in WordPress

Custom post types are one of the more useful features in WordPress. In this article, we will show you how to create custom post types in WordPress.

Creating custom post type the Easy way you can create manually  custom post type by adding the required code in your theme’s functions.php file

// Our custom post type function
function create_posttype() {
    register_post_type( 'custompost',
    // CPT Options
        array(
            'labels' => array(
                'name' => __( 'custompost' ),
                'singular_name' => __( 'custompost' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'custompost'),
        )
    );
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );
Register post type custompost name in label.
Querying by Post Type

In any template file of the WordPress theme system, you can also create new queries to display posts from a specific post type. This is done via the post_type argument of the WP_Query object.

Example

$args = array( 'post_type' => 'custompost ', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); whil e ( $loop->have_posts() ) : $loop->the_post(); the_title(); echo '<div class="entry-content">'; the_content(); echo '</div>'; endwhile;

Displaying Custom Post Types on The Front Page

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
    if ( is_home() && $query->is_main_query() )
        $query->set( 'post_type', array( 'post', 'custompost' ) );
    return $query;
}
Social Share

Leave a Comment