How to add custom field to custom post type?

Cynthia picture Cynthia · Jul 31, 2012 · Viewed 26.1k times · Source

Good morning.

I have created a custom post type called 'Products'. I want to create a custom field (is metabox the correct term?) where my client can tick a box to determine whether a given post within this CPT is a featured post.

Here is the code in my functions.php to create the 'Products' CPT:

function products_custom_init() {

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

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => false,
        'query_var' => true,
        'rewrite' => array('slug','pages'),
        'capability_type' => 'post',
        'hierarchical' => true,
        'menu_position' => 5,
        'supports' => array('title','editor','thumbnail','excerpt',)
      );

    register_post_type( 'products' , $args );
}
add_action( 'init', 'products_custom_init' );

So how do I add the 'featured' metabox / custom field to only Products posts?

Many thanks,

Cynthia

Answer

janw picture janw · Jul 31, 2012

As Muhammad Yasin said there are plugins I'd recommend:
http://wordpress.org/extend/plugins/more-fields/

if you want to do it yourself in code look at: add_meta_box

<?php add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args ); ?>

You can register boxes per post type.