Add custom image type Metabox in Wordpress

Asked

Viewed 396 times

1

I am beginner in Wordpress and I am developing a theme for a blog in it and I need to create a presentation where there is a brief summary of the blogger plus her photo. Well, I created a kind of post called presentation and within it I want to insert a field (Metabox) type image, the one where you can explore the Wordpress library or upload again. Is there any way to do that?

Another question: I am not able to save the value of the photo field, because it is file type?

My functions.php file

// cria a pagina apresentacao no admin
function type_post_apresentacao() {
    $labels = array(
        'name' => _x('Apresentação', 'post type general name'),
        'singular_name' => _x('Apresentação', 'post type singular name')
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'register_meta_box_cb' => 'apresentacao_meta_box',
        'supports' => array('title','editor','thumbnail', 'revisions')
    );

  register_post_type( 'apresentacao' , $args );
  flush_rewrite_rules();
}

// Cria a meta_box
function apresentacao_metabox() {
 // Tipos de post para a metabox
   $screens = array( 'post', 'page', 'apresentacao' );
   foreach ( $screens as $screen ) {
     add_meta_box(
     'apresentacao_meta_box',          // ID da Meta Box
     'Imagem de perfil',   // Título
     'apresentacao_metabox_callback',  // Função de callback
     $screen,                    // Local onde ela vai aparecer
     'normal',                   // Contexto
     'high'                      // Prioridade
     );
   }
}

// Essa é a função que vai exibir os dados para o usuário
function apresentacao_metabox_callback( $post ) {
 wp_nonce_field( 'apresentacao_custom_metabox', 'apresentacao_custom_metabox_nonce' );
 $foto = get_post_meta( $post->ID, '_tp_post_foto', true );
 echo '<pre>';
 var_dump($post);
 echo '</pre>';
 echo "<input id='foto' type='file' value='$foto' name='_tp_post_foto' />";
}
function apresentacao_save_custom_metabox_data( $post_id ) {
  update_post_meta( $post_id, '_tp_post_foto', $foto );
}
// add actions
add_action('init', 'type_post_apresentacao');
add_action( 'save_post', 'apresentacao_save_custom_metabox_data' );
add_action( 'add_meta_boxes', 'apresentacao_metabox', 1 );

This is the $post var_dump

object(WP_Post)#5363 (24) {
  ["ID"]=>
  string(2) "56"
  ["post_author"]=>
  string(1) "1"
  ["post_date"]=>
  string(19) "2017-07-31 11:09:10"
  ["post_date_gmt"]=>
  string(19) "2017-07-31 14:09:10"
  ["post_content"]=>
  string(6) "dsadas"
  ["post_title"]=>
  string(9) "dasdasdas"
  ["post_excerpt"]=>
  string(0) ""
  ["post_status"]=>
  string(7) "publish"
  ["comment_status"]=>
  string(6) "closed"
  ["ping_status"]=>
  string(6) "closed"
  ["post_password"]=>
  string(0) ""
  ["post_name"]=>
  string(9) "dasdasdas"
  ["to_ping"]=>
  string(0) ""
  ["pinged"]=>
  string(0) ""
  ["post_modified"]=>
  string(19) "2017-07-31 11:09:10"
  ["post_modified_gmt"]=>
  string(19) "2017-07-31 14:09:10"
  ["post_content_filtered"]=>
  string(0) ""
  ["post_parent"]=>
  string(1) "0"
  ["guid"]=>
  string(68) "http://localhost/wordpress/?post_type=apresentacao&p=56"
  ["menu_order"]=>
  string(1) "0"
  ["post_type"]=>
  string(12) "apresentacao"
  ["post_mime_type"]=>
  string(0) ""
  ["comment_count"]=>
  string(1) "0"
  ["filter"]=>
  string(4) "edit"
}

1 answer

1


The process to create an uploading field using native Wordpress modes is a little different, just load the right libraries and create a text input, or Hidden, to save the value.

Something like this, on the page where your field goes, use:

// Carrega as bibliotecas javascript necessárias para usar os modais
if ( ! did_action( 'wp_enqueue_media' ) ){
    wp_enqueue_media();
}

Now, assuming your input is:

<input id="foto" name="foto" type="text" value="" />
<button id="escolher">Escolher imagem</button>

You use the following javascript to call the modal:

// Quando o botão #escolher for clicado
// Abre a janela do editor, e quando uma 
// imagem for selecionada insere o ID dela como valor do campo #foto
$('#escolher').click(function(){
    wp.media.editor.send.attachment = function(props, attachment){          
        $('#foto').val(attachment.url);
    }
    wp.media.editor.open(this);
    return false;
});

Now the field #foto behaves like any input from your page. You can use the filter save_post to fetch the value (which will be in the key $_POST['foto'] and save using update_post_meta.

  • It worked. Thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.