Antes de añadir un meta box a un “custom post type” necesitamos crear un custom post type.
Echa un vistazo a esta clase completa para crear un custom post type desde un plugin.

Así que siguinedo con este ejemplo nuestro custom post type es cpt_examples

En la función constructora __construct de nuestra clase para crear custom post type añade las siguientes líneas:

1
2
add_action( 'add_meta_boxes', array( $this, 'add_meta_box') );
add_action( 'save_post',      array( $this, 'save_meta_box_data' ) );

Y después crea las funciones en la clase.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * add_meta_box
 */
public function add_meta_box(){
 
	add_meta_box( 'cpt_examples_meta', 'CPT Examples Extra Info', array( $this, 'display_meta_form' ), 'cpt_examples', 'advanced', 'high' );
}
 
/**
 * display_meta_form	
 */
 
public function display_meta_form( $post ) {
 
	wp_nonce_field( 'cptexamples_meta_box', 'cptexamples_meta_box_nonce' );
 
	$my_first_field  = get_post_meta( $post->ID, 'cpt_first_meta_field', true );
	$my_second_field = get_post_meta( $post->ID, 'cpt_second_meta_field', true );
 
		echo '<div class="wrap">';
		echo '<label for="cpt_first_meta_field">' . _e( 'First Meta Field', 'cpt_domain' ) . '</label> <br/>';
		echo '<input class="text" type="text" id="cpt_first_meta_field" name="cpt_first_meta_field" value="' . esc_attr( $my_first_field ) . '"   />';
		echo '</div>';
 
		echo '<div class="wrap">';
		echo '<label for="cpt_second_meta_field">' . _e( 'Second Meta Field', 'cpt_domain' ) . '</label>  <br/>';
		echo '<input class="text" type="text" id="cpt_second_meta_field" name="cpt_second_meta_field" value="' . esc_attr( $my_second_field ) . '"   />';
		echo '</div>';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * save_meta_box_data
 * función llamada en el hook save_post para validar y guardar los datos.
 */
 
public function save_meta_box_data( $post_id ){
 
  // Verificar que se ha declarado el nonce.
    if ( ! isset( $_POST['cptexamples_meta_box_nonce'] ) ) {
	  return;
    }
 
  // Verificar que el nonce es válido.
    if ( ! wp_verify_nonce( $_POST['cptexamples_meta_box_nonce'], 'cptexamples_meta_box' ) ) {
	   return;
    }
 
  // Si es un autoguardado no debe hacer nada.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
	  return;
    }
 
  // Verificar los permisos del usuario.
    if ( isset( $_POST['post_type'] ) && $_POST['post_type'] == 'cpt_examples' ) {
            if ( ! current_user_can( 'edit_page', $post_id ) ) {
		     return;
	    }
 
    } else {
            if ( ! current_user_can( 'edit_post', $post_id ) ) {
		     return;
	    }
    }
 
   // Guardar la información en la base de datos
       if ( isset( $_POST['cpt_first_meta_field'] ) ) {
 
             $my_first_meta_field = sanitize_text_field( $_POST['cpt_first_meta_field'] );
	     update_post_meta( $post_id, 'cpt_first_meta_field', $my_first_meta_field );
	}
 
       if ( isset( $_POST['cpt_second_meta_field'] ) ) {
 
             $my_second_meta_field = sanitize_text_field( $_POST['cpt_second_meta_field'] );
	     update_post_meta( $post_id, 'cpt_second_meta_field', $my_second_meta_field );
	}
 
 
}

También visita este otro snippet para posicionar el metabox justo después del título dentro del formulario.

Añadir meta box a un “custom post type”
Etiquetado en:    

3 pensamientos en “Añadir meta box a un “custom post type”

  • mayo 22, 2017 a las 10:57
    Enlace permanente

    фотосессия в стиле позы для беременных . зимние фотосессии влюбленных интересные места для фотосессий в москве необычная фотосессия беременных аксессуары для фотосессии беременных что одеть на новогоднюю фотосессию беременная фотосессия зимой . фотосессия беременных на природе оригинальные фото беременных зимние фотосессии пар фотосессия в москве недорого. фотографа на крестины недорого в москве образы для фотосессии зимой беременная девушка с мужем идеи беременной фотосессии .

    Responder
  • octubre 23, 2018 a las 09:54
    Enlace permanente

    Thanks for visiting,
    I’m Bethany.
    If you’ve ever been too busy and couldn’t finish a research paper , then you’ve come to the right place. I work with students in all areas of the writing technique. I can also write the assignment from start to finish.
    My career as an academic writer started early in college . After learning that I was very skilled in the field of academic writing, I decided to take it up as a profession.

    Professional Academic Writer- Bethany Haynes- Quality-Content-Writing Team

    Responder
  • julio 8, 2019 a las 12:32
    Enlace permanente

    Hi guys, it’s Amber Crouch here!
    I work as an academic writer and have created this content with the intent of changing your life for the better. I started honing my writing skills in college. I learned that my fellow students needed writing help—and they were willing to pay for it. The money was enough to help pay my tuition for my remaining semesters of college.
    Ever since high school, I have continued to work as an academic writer. I was hired by a writing company based in the United Kingdom. Since then, the dissertations that I have written have been sold around Europe and the United States.
    In my line of work, I have become used to hearing, “Amber, can you help me meet my writing assignment deadline?” I know that I can provide this service.

    Academic Writer – Amber Crouch – Click here Company

    Responder

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *