DIGITALREP

How to add WordPress custom post typesOctober 16, 2013

Add your WordPress custom post type to functions.php

Say we want to add a custom product post type. We first need to create an array of labels to be used in the administrative menu for the post type:

$labels = array( 'name' => _x('Products', 'post type general name'), 'singular_name' => _x('Product', 'post type singular name'), 'add_new' => _x('Add New', 'Product'), 'add_new_item' => __('Add New Product'), 'edit_item' => __('Edit Product'), 'new_item' => __('New Product'), 'all_items' => __('All Products'), 'view_item' => __('View Product'), 'search_items' => __('Search Products'), 'not_found' => __('No products found'), 'not_found_in_trash' => __('No products found in the Trash'), 'parent_item_colon' => '', 'menu_name' => 'Products' );


We also need to create another array named args and add the labels array to it along with a description, access level, position in the menu, and whether or not its archivable / searchable:

$args = array( 'labels' => $labels, 'description' => 'Holds data about products', 'public' => true, 'menu_position' => 1, 'supports' => array('title', 'editor'), 'has_archive' => false, 'exclude_from_search' => true );

Then we simply register the custom post type:

register_post_type(‘products’, $args);

Add an icon

To have a little icon show up next to it in the administrative panel specify the image you’d like to use in the background image property of #menu-posts-name_of_your_custom_post_type .wp-menu-image:

#menu-posts-products .wp-menu-image { background: url('/images/application-blog.png') no-repeat 6px -18px !important; } #menu-posts-products:hover .wp-menu-image { background-position: 6px 6px !important; }

To access a custom post type

$args = array('post_type' => 'products', 'posts_per_page' => 10); $loop = new WP_Query($args); $i = 0; while($loop->have_posts()) { $loop->the_post(); the_content(); }

Category: Tutorials
Tags:  

Leave a Reply

Your email address will not be published. Required fields are marked *