21 Oct 2019

how to add custom field in custom post type wordpress

This is the hardest of the lot. It’s not really hard though, just alot of HTML to make the meta boxes. You can put any HTML you like in meta boxes, I just like to keep mine looking like standard WP fields:


<?php
/**
 * Add cafe custom fields
 */
function add_cafe_meta_boxes() {
 add_meta_box("cafe_contact_meta", "Contact Details", "add_contact_details_cafe_meta_box", "cafes", "normal", "low");
}
function add_contact_details_cafe_meta_box()
{
 global $post;
 $custom = get_post_custom( $post->ID );
 
 ?>
 <style>.width99 {width:99%;}</style>
 <p>
  <label>Address:</label><br />
  <textarea rows="5" name="address" class="width99"><?= @$custom["address"][0] ?></textarea>
 </p>
 <p>
  <label>Website:</label><br />
  <input type="text" name="website" value="<?= @$custom["website"][0] ?>" class="width99" />
 </p>
 <p>
  <label>Phone:</label><br />
  <input type="text" name="phone" value="<?= @$custom["phone"][0] ?>" class="width99" />
 </p>
 <?php
}
/**
 * Save custom field data when creating/updating posts
 */
function save_cafe_custom_fields(){
  global $post;
 
  if ( $post )
  {
    update_post_meta($post->ID, "address", @$_POST["address"]);
    update_post_meta($post->ID, "website", @$_POST["website"]);
    update_post_meta($post->ID, "phone", @$_POST["phone"]);
  }
}
add_action( 'admin_init', 'add_cafe_meta_boxes' );
add_action( 'save_post', 'save_cafe_custom_fields' );


Custom Templates

You may want your new post type to look different from standard posts. This can be done using custom templates. The WordPress codex cover custom post type templates nicely but I’ll quickly go over what I did for completeness. I’m using twentytwelve theme in my demo but this should apply for most themes.
  1. Duplicate single.php into single-<post type>.php
  2. Replace
    <?php get_template_part( 'content', get_post_format() ); ?>
    with
    <?php get_template_part( 'content', '<post type>' ); ?>
  3. Duplicate content.php into content-<post type>.php and modify however you like




Reference Links: