• Решено Reebok532

    (@reebok532)


    Здравствуйте. Помогите пожалуйста решить проблему с добавлением метабоксов на страницы медиафайлов и сохранением данных из них. С самим добавлением проблем не возникает.
    Допустим используя простейший пример их кодекса — http://codex.wordpress.org/Function_Reference/add_meta_box

    <?php
    /* Define the custom box */
    
    add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
    
    // backwards compatible (before WP 3.0)
    // add_action( 'admin_init', 'myplugin_add_custom_box', 1 );
    
    /* Do something with the data entered */
    add_action( 'save_post', 'myplugin_save_postdata' );
    
    /* Adds a box to the main column on the Post and Page edit screens */
    function myplugin_add_custom_box() {
        $screens = array( 'attachment' );
        foreach ($screens as $screen) {
            add_meta_box(
                'myplugin_sectionid',
                __( 'My Post Section Title', 'myplugin_textdomain' ),
                'myplugin_inner_custom_box',
                $screen
            );
        }
    }
    
    /* Prints the box content */
    function myplugin_inner_custom_box( $post ) {
    
      // Use nonce for verification
      wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
    
      // The actual fields for data entry
      // Use get_post_meta to retrieve an existing value from the database and use the value for the form
      $value = get_post_meta( $_POST['post_ID'], $key = '_my_meta_value_key', $single = true );
      echo '<label for="myplugin_new_field">';
           _e("Description for this field", 'myplugin_textdomain' );
      echo '</label> ';
      echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.esc_attr($value).'" size="25" />';
    }
    
    /* 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 ( !isset( $_POST['myplugin_noncename'] ) || !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
    
      //if saving in a custom table, get post_ID
      $post_ID = $_POST['post_ID'];
      //sanitize user input
      $mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
    
      // Do something with $mydata
      // either using
      add_post_meta($post_ID, '_my_meta_value_key', $mydata, true) or
        update_post_meta($post_ID, '_my_meta_value_key', $mydata);
      // or a custom table (see Further Reading section below)
    }
    ?>

    На странице медиафайла появляется новое поле с возможностью редактирования, но после обновления самого медиафайла, данные из этого поля не сохраняются !!!

    Испробовал разные методы, ничего не помогает, помогите пожалуйста решить этот вопрос.

    Если добавлять эти поля для простых постов или страниц, все данные нормально сохраняются !

Просмотр 6 ответов — с 1 по 6 (всего 6)
  • используя простейший пример их кодекса

    Если это простейший пример, Вам и флаг в руки. Тем более Вы даже не упомянули что и куда собираетесь сохранять. Можно, конечно, догадаться, что надо сохранить мета данные.

    Автор Reebok532

    (@reebok532)

    что и куда собираетесь сохранять

    данные из этого поля не сохраняются !!!

    ну как же не упомянул ?

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

    Я не спец в этом, но мб пример у Тимура поможет.

    Автор Reebok532

    (@reebok532)

    Я не спец в этом, но мб пример у Тимура поможет.

    Спасибо, но результат тот же !

    поле не обновляется, данные не сохраняются !

    up

    ?? На всякий случай ознакомьтесь с правилами форума..
    Попробуйте этот вариант
    http://wordpress.stackexchange.com/questions/14500/custom-fields-for-attachments

    Автор Reebok532

    (@reebok532)

    Попробуйте этот вариант
    http://wordpress.stackexchange.com/questions/14500/custom-fields-for-attachments

    Спасибо огромное !!! Все работает)

Просмотр 6 ответов — с 1 по 6 (всего 6)
  • Тема «add_meta_box для медиафайла !» закрыта для новых ответов.