support

Creating Custom Post Types by PHP code

There are two methods by which we can use to create our own custom post types:

1. By Using Plugins
2. By Using hard code into your theme’s functions.php file.

Custom Post Type UI” is a nice plugin that allows you to easily create custom post types as well as taxonomies.
This also provides PHP code to create custom post types, so you can use it into your theme’s functions.php file.

If you want to use custom post types without a plugin, then just add the following PHP code to your functions.php file:


// Creating Videos a Custom Post Type
register_post_type('videos', array(
'label' => 'Videos',
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug' => 'videos'),
'query_var' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'thumbnail',
'author',
'page-attributes',)
) );

Explanation :

register_post_type( $post_type, $args ): This function accepts two parameters, $post_type or the name of the post type, and $args, an array of arguments.

label: Plural name given to the post type which is displayed in the admin panel sidebar.

public: true/false. Allows the admin UI to be populated with posts of this type.

show_ui: true/false. Shows or hides a default UI to mange this post type.

capability_type: Default: post Post type to use for checking read, edit, and delete capabilities.

hierarchical: Whether the post type is hierarchical.

rewrite: true/false. Default: true If slug argument is entered then the slug name is prepended to the posts.

query_var: true/false Sets the post type name as a query variable.

supports: Default: title and author Sets different support features the post type allows.

Please visit WordPress Codex for more detail information on register_post_type().

Displaying Your Custom Post Type Posts

To display the posts from your custom post type, add the following codes in the loop. Replace “name” with the name of your post type. Note: You don’t have to add the custom post types in your index.php file. You can create a Custom WordPress page and run the following query within the Loop.

$query = new WP_Query( 'post_type=name' );

To display posts from more than one post type, change the above code to the following. Change movies with your custom post type name.

$query = new WP_Query( array(
'post_type' => array( 'post', 'videos' )
) );

The above code will display all the post from the regular post type (post) and from the custom post type, videos.

© 2008-2021 Copyright Startbit IT Solutions Pvt. Ltd.(Formerly known as Vivacity InfoTech Pvt. Ltd.) | All Rights Reserved.
Loading...