Wordpress Series: Creating a Custom Post Type (Part 1)

in #utopian-io7 years ago

This is yet another episode of the wordpress tutorial series that I initiated few weeks back. In case you missed the recent episodes, you can find a list towards the end of the article.

In today's session, we will focus on the concept of 'custom post types', what are they, why would we need them, and how to create them. This is the first part of our custom post type series, and in following episodes we will highlight defining specific content to those post types, and handling adding/editing/saving as well as the display of those post types.

image.png

Custom Post Type

A custom post type is basically wordpress' answer to allow creating and storing practically any type of entity and/or objects within your wordpress site.
Again to refresh your memories, wordpress started initially as a blogging platform, so their standard entity for storage is the post (article), yet they allowed expanding this beyond simple articles via the custom post types. Similarly to posts, custom posts also support several values to be stored, whether in the shape of standard post information such as the title, description, url, image,... or even custom meta data that we need to store, which is additional information not available by default within wordpress.
I recall from early in the days of my university programming years, when we were first introduced to the concept of objects, the first example they gave us of objects was, cars.
So let us take that as our standard example today, and consider our wordpress site needs to store and display cars and car information, maybe a website to sell cars. So how do we add support to our wordpress site for car entities?

Creating our Car custom post type

While many opt for using plugins to create custom post types, and yes that is a valid option, yet my personal preference is to code my way through it, due to certain complexities of some plugins and the additional heaviness they impose onto your wordpress solution.
So now, in order to create a custom post type, we will need to either do that via a plugin, or via the functions.php file. Both options are valid, it only depends how large your custom post type would be. Since we already covered creating plugins in a prior session, I will not repeat myself and you can check this out here Wordpress Series: Coding Your Way Via Plugins and then go ahead and create that standard plugin of yours within which you will need to append your following code/steps.

Registering the Car post type

In order for wordpress to recognize Cars as valid post types, and allow us to interact with them, we will need to first register the post type. This is essentially done utilizing a built-in wordpress functionality:

register_post_type( 'car', $args );

This built-in function would take the first param to be the CPT (custom post type) name, along with a set of arguments (args) that wordpress requires to learn about this new post type.

The set of needed arguments comes in the shape of a two-dimensional array with a set of values identifying the custom post type, including:

  • the label and description for the post type.
  • a set of labels identified as another two-dimensional array and used to render the content of the relevant custom post type, including name, singular_name, menu_name, view_item, search_items. Below would be a sample array that identifies a portion of those fields:
    $labels = array(
            'name'                  => _x( 'Cars', 'Post Type General Name', 'car' ),
            'singular_name'         => _x( 'Car', 'Post Type Singular Name', 'car' ),
            'menu_name'             => __( 'Cars', 'car' ),
            'name_admin_bar'        => __( 'Car', 'car' ),
            'archives'              => __( 'Car Archives', 'car' ),
    );
  • a set of pre-existing built-in wordpress object variables, under the supports key
  • a set of associated categories/taxonomies under the taxonomies key
  • the hierarchical flag which decides whether the post type supports hierarchical structure (such as wordpress posts) or just plain structure (such as wordpress pages)
  • the public flag which defines whether this post will be publicly visible to authors/readers, combined with exclude_from_search and publicly_queryable which control visibility within search and external indexing/querying.
  • show_ui, show_in_menu, menu_position,... control whether this post type will be available for display under specific menus in the wordpress back end system, and how it will show.
  • can_export and has_archive allow controlling whether the entries in this post type can be exported, and whether cars can be listed as archive list under wordpress.
  • capability_type this defines how the car type will interact with wordpress system. The standard approach is to treat this as similarly to how posts function.
    For a complete listing and further details about all these parameters, you can check out the official wordpress documentation for the register_post_type functionality found in here

Now adding this register_post_type function cannot be done at random, or at any instance in time, it needs to be called within a specific hook within wordpress called 'init' and at priority 0, so that the whole custom post type is registered at the proper moment and made available for later interactions with wordpress.

add_action( 'init', 'gk_create_car_type', 0 );

where the gk_create_car_type is the function that contains the full coding that we described above to create the custom post type, and which we will show below in the following section.
Also keep in mind that in wordpress, a common best practice to allow extensibility and avoid function overriding issue, is to wrap functions within

if ( ! function_exists('gk_create_car_type') ) 

The Full Coding

Wrapping all the above together, we end up with the following script ready to be incorporated into wordpress.
I have created a gist accessible here so that you can properly copy and paste the code should you need to, especially that the markdown code section can convert some characters improperly :)
you can also see a quick screenshot below of that same full code

image.png

Photo Credits: Images in this post are either self-created, or are CC images publicly available and labeled for reuse under google search.

Prior entries in this series:
If you missed them, here they are !


Founder of Arab Steem
Arab Steem is a community project to expand Steemit to the Arab world, by supporting the existing Arab steemians and promoting others to join.
You can connect with us on @arabsteem or via discord channel https://discord.gg/g98z2Ya
Your support is well appreciated!

Proud Member Of

  • steemSTEM: SteemSTEM is a project that aims to increase both the quality as well as visibility of Science, Technology, Engineering and Mathematics (and Health). You can check out some great scientific articles via visiting the project tag #steemSTEM , project page @steemstem, or connecting with us on chat https://steemit.chat/channel/steemSTEM
  • MAP(Minnows Accelerator Project): MAP is a growing community helping talented minnows accelerate their growth on Steemit.
    To join, check out the link at the home page of @accelerator account
  • Steemitbloggers: #Steemitbloggers is a community supporting bloggers with authentic and awesome content!
    To join check out the discord channel https://discordapp.com/invite/gRypnga

Thanks again!

@mcfarhat



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Good post,
[FR] J' avais déjà fait un site WordPress mais je n' étais pas allé aussi loin ^^

merci cher Zonguin! Wordpress c'est un monde !

thanks for sharing dear brother.

Thanks Khaled!

very use full! wordpress gives most of themes for beginners ...thanks for sharing

Qurator
Your Quality Content Curator
This post has been upvoted and given the stamp of authenticity by @qurator. To join the quality content creators and receive daily upvotes click here for more info.

Qurator's exclusive support bot is now live. For more info click HERE or send some SBD and your link to @qustodian to get even more support.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @mcfarhat I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • You are generating more rewards than average for this category. Super!;)
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

I rilli like ur work...wud like to be like u soon

thanks for sharing,all the best 🌹

nice piece... Great stuff

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63651.41
ETH 2679.55
USDT 1.00
SBD 2.80