Suporte » Desenvolvendo com WordPress » Custom Post Type perde quando o wordpress salva o Rascunho

  • Resolvido Darkphv

    (@darkphv)


    Seguinte, eu tenho um custom post que suporta ‘title’, ‘editor’ e um metabox URL, eu preencho o campo URL e quando vou preencher o título e apos o editor o wordpress automaticamente salva os campos Title e Editor mas não salva o metabox que eu criei, deixando em branco, causando confusão. alguém sabe como eu faço para salvar também o meu metabox quando o wordpress salva automaticamente o post???

Visualizando 4 respostas - 1 até 4 (de um total de 4)
  • Vc criou alguma action pra salvar o campo?

    Se não use isto:

    /* Do something with the data entered */
    add_action( 'save_post', 'myplugin_save_postdata' );
    
    /* When the post is saved, saves our custom data */
    function myplugin_save_postdata( $post_id ) {
      // verify if this is an auto save routine.
      // If it is our form has not been submitted, so we dont want to do anything
      if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
          return;
    
      // verify this came from the our screen and with proper authorization,
      // because save_post can be triggered at other times
    
      if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
          return;
    
      // Check permissions
      if ( 'page' == $_POST['post_type'] )
      {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return;
      }
      else
      {
        if ( !current_user_can( 'edit_post', $post_id ) )
            return;
      }
    
      // OK, we're authenticated: we need to find and save the data
    
      $mydata = $_POST['myplugin_new_field'];
    
      // Do something with $mydata
      // probably using add_post_meta(), update_post_meta(), or
      // a custom table (see Further Reading section below)
    
       return $mydata;
    }

    CODEX

    Criador do tópico Darkphv

    (@darkphv)

    Entao eu coloquei tal codigo mas nao funciona, ele nem esta salvando agora.

    Veja como estou criando o custom post e como salvo o novo meta dado

    //--------------Postar Fotos Revistas----------
    add_action('init', 'type_post_imgrevista');
    function type_post_imgrevista()
    {
        $labels = array(
            'name'=>_x('Revista', 'post type general name'),
            'singular_name'=>_x('Revista', 'post type singular name'),
            'add_new'=>_x('Adicionar Nova Imagem', 'Novo item'),
            'add_new_item'=>__('Nova Imagem'),
            'edit_item'=>__('Editar Imagem'),
            'new_item'=>__('Novo Item'),
            'view_item'=>__('Ver Item'),
            'search_items'=>__('Procurar Itens'),
            'not_found'=>__('Nenhum registro encontrado'),
            'not_found_in_trash'=>__('Nenhum registro encontrado na lixeira'),
            'parent_item_colon'=>'',
            'menu_name'=>'Img Revista'
        );
    
        $args = array(
            'labels'=>$labels,
            'public'=>true,
            'public_queryable'=>true,
            'show_ui'=>true,
            'query_var'=>true,
            'rewrite'=>true,
            'capability_type'=>'post',
            'hierarchical'=>false,
            'menu_position'=>5,
            'register_meta_box_cb'=>'url_meta_box_revista',
            'menu_icon'=>WEBELEVEN_PLUGIN_URL . '/img/icone.png',
            'supports'=>array('title', 'thumbnail')
                //'supports' => array('title', 'editor', 'thumbnail', 'comments', 'excerpt', 'custom-fields', 'revisions', 'trackbacks')
        );
        register_post_type('revista', $args);
        flush_rewrite_rules();
    }
    function url_meta_box_revista()
    {
        add_meta_box('meta_box_url', __('Url'), 'meta_box_meta_url_revista', 'revista', 'normal', 'high');
    }
    
    function meta_box_meta_url_revista()
    {
        global $post;
        $metaBoxurl = get_post_meta($post->ID, 'url_meta', true);
        ?>
        <label for="inputurlMeta">Url: </label>
        <input type="text" name="url_meta" id="inputurlMeta" size="120" value="<?php echo $metaBoxurl; ?>" />
        <?php
    }
    add_action('save_post', 'save_url_post_revista');
    function save_url_post_revista()
    {
        update_post_meta($post->ID, 'url_meta', $_POST['url_meta']);
    }

    Gostaria de saber se estou salvando errado?

    Criador do tópico Darkphv

    (@darkphv)

    Ainda nao consegui resolver o problema, ninguem sabe outra solucao?? Faz tempo que to com esse erro! muito obrigado pela atencao!!

    O problema é que na função de salvamente não basta adicionar o upadate_post_meta é necessário fazer algumas verificações como foi mostrado na mensagem anterior a sua pelo Willian.

    Isso é necessário nesta função

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
          return;
    
      // verify this came from the our screen and with proper authorization,
      // because save_post can be triggered at other times
    
      if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
          return;
    
      // Check permissions
      if ( 'page' == $_POST['post_type'] )
      {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return;
      }
      else
      {
        if ( !current_user_can( 'edit_post', $post_id ) )
            return;
      }

    Sem isso vai continuar dando problema

    Outra coisa é que se deve pegar o valor e fazer comparação se ele foi alterado ou então o campo nunca fica sendo atualizado corretamente ou sempre atualizando mesmo não sendo necessário.

Visualizando 4 respostas - 1 até 4 (de um total de 4)
  • O tópico ‘Custom Post Type perde quando o wordpress salva o Rascunho’ está fechado para novas respostas.