Create Custom Post Type
From a blog WordPress has become a flexible & powerful content management system, it can handle any type of website project. If you are a WordPress developer then you must have used CPT in past. Custom Post Types are like Posts and Pages, post type can be any kind of content. By default WordPress comes wih below Post Types
- Navigation Menus
- Custom CSS
Custom Post Types are the content you can get more details from official site WP codex CPT
Let’s open post_type.php within include directory and add the following code in it.
In Custom WooCommerce Plugin Development there is a chance that you declare same function which already exists. For this WordPress provides us a very useful function function_exists() to check existing ones.
register_post_type() is used for registering Custom Post Types. Post types can support any number of built-in core features such as meta boxes, custom fields, post thumbnails, post statuses, comments, and more. See the
$supports argument for a complete list of supported features. To check more details on CPT and its parameters Click register_post_type
The init action hook fires after WordPress has finished loading but before any headers are sent.
Now your Admin Dashboard should show Manufacturer Custom Post Type like below image. You can now view Add, Edit and listing pages.
Add Manufacturer to WooCommerce Product
WordPress Plugins can add custom meta boxes to an edit screen of any post type. Meta box is a draggable box shown on the post editing screen. Its allows the user to select or enter the post related information. In edit screen Editor, Publish, Categories, Tags, etc. These all boxes are meta boxes.
Below are things I’ll do for Manufacturer Meta Box.
- Creating meta boxes
- Using meta boxes with post type
- Handling data validation
- Saving custom meta data
Its time to add the Manufacturers dropdown to the WooCommerce Product Add/Edit pages. Open meta_box.php file and add following code
Action hook add_meta_boxes triggers the function manufacturer_meta_box_add(). The add_meta_box() function adds meta boxes on specified location e.g right sidebar of products edit page. It contains callback function meta_box_manufacturer() that fills the box with the desired content. To store meta box submitted data in database meta_box_save() function is attached to save_post action hook.
Display Manufacturer in Product Listing
For ease the client wants to display Manufacturers on Products listing page. WordPress provides manage column filter hook to add new column within listings. The function add_product_manufacturer() adds Manufacturer column.
Add the following code to add_column.php file with include/admin directory
The function render_product_column_manufacturer() is attached to manage_product_posts_custom_column hook to displays product manufacturers. It contains WordPress get_post_meta() function that retrieves meta data from wp_post_meta database table.