2014-01-06 3 views
0

Я создаю пользовательские поля для отправки, все текстовые поля работают нормально, но я немного смущен в сохранении поля вложения. его имя файла сохранения в базе данных, но не перемещение этого файла в каталоге загрузки. enter image description hereWordpress пользовательские поля для прикрепления сообщений

вот код:

`$ sp_boxes = массив ( 'Подробнее' => массив (

array('author', 'Author/product:'), //text field 
    array('filesize', 'File size/license:'),//text field 
    array('abc', 'Requirements: '),//text field 
    array('screen', 'Screen Shots: ',"img"),//Attachment Field 

),` 

* Attachemnet (поле загрузки изображения запутанным) add_action('admin_menu', 'sp_add_custom_box'); // Используйте действие save_post, чтобы что-то сделать с введенными данными. // Сохранение настраиваемых полей add_action('save_post', 'sp_save_postdata', 1, 2); // Добавляет пользовательский раздел в «расширенный» Po st и page edit screen

`function sp_add_custom_box() { global $ sp_boxes;

if (function_exists('add_meta_box')) { 

    foreach (array_keys($sp_boxes) as $box_name) { 
     add_meta_box($box_name, __($box_name, 'sp'), 'sp_post_custom_box', 'post', 'normal', 'high'); 
    } 
} 
} 

function sp_post_custom_box ($obj, $box) { 
global $sp_boxes; 
static $sp_nonce_flag = false; 

// Run once 
if (! $sp_nonce_flag) { 
    echo_sp_nonce(); 
    $sp_nonce_flag = true; 
} 

// Genrate box contents 
foreach ($sp_boxes[$box['id']] as $sp_box) { 
    echo field_html($sp_box); 
} 
} 

function field_html ($args) { 

switch ($args[2]) { 

    case 'textarea': 
     return text_area($args); 

    case 'checkbox': 
     // To Do 

    case 'radio': 
     // To Do 

    case 'text': 
    case 'img': 
    return attachment($args); 
    default: 
     return text_field($args); 
} 
} 

function attachment ($args) { 
global $post; 

// adjust data 
$args[2] = get_post_meta($post->ID, $args[0], true); 
$args[1] = __($args[1], 'sp'); 

$label_format = 
     '<label for="%1$s">%2$s</label><br />' 
    . '<input type="file" id="%1$s" name="%1$s" value="" size="25"><br /><br />'; 

return vsprintf($label_format, $args); 
} 
function text_field ($args) { 
global $post; 

// adjust data 
$args[2] = get_post_meta($post->ID, $args[0], true); 
$args[1] = __($args[1], 'sp'); 

$label_format = 
     '<label for="%1$s">%2$s</label><br />' 
    . '<input style="width: 95%%;" type="text" name="%1$s" value="%3$s" /><br /><br />'; 

return vsprintf($label_format, $args); 

}

`

  • И это, как я храню пост данных

` функция sp_save_postdata ($ post_id, $ пост) { глобальные $ sp_boxes;

// 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['sp_nonce_name'], plugin_basename(__FILE__))) { 
    return $post->ID; 
} 

// Is the user allowed to edit the post or page? 
if ('page' == $_POST['post_type']) { 
    if (! current_user_can('edit_page', $post->ID)) 
     return $post->ID; 

} else { 
    if (! current_user_can('edit_post', $post->ID)) 
     return $post->ID; 
} 

// OK, we're authenticated: we need to find and save the data 
// We'll put it into an array to make it easier to loop though. 

// The data is already in $sp_boxes, but we need to flatten it out. 
foreach ($sp_boxes as $sp_box) { 
    foreach ($sp_box as $sp_fields) { 
     $my_data[$sp_fields[0]] = $_POST[$sp_fields[0]]; 
    } 
} 

// Add values of $my_data as custom fields 
// Let's cycle through the $my_data array! 
foreach ($my_data as $key => $value) { 
    if ('revision' == $post->post_type ) { 
     // don't store custom data twice 
     return; 
    } 

    // if $value is an array, make it a CSV (unlikely) 
    $value = implode(',', (array)$value); 

    if (get_post_meta($post->ID, $key, FALSE)) { 


     // Custom field has a value. 
     update_post_meta($post->ID, $key, $value); 


    } else { 

     // Custom field does not have a value. 
     add_post_meta($post->ID, $key, $value); 
    } 

    if (!$value) { 
enter code here 
     // delete blanks 
     delete_post_meta($post->ID, $key); 
    } 
} 
}` 

Все работает нормально загрузить поле изображения сохранить имя изображения в БД, но изображение не движется, чтобы загрузить каталог. Кто-нибудь может мне помочь ??? благодаря

+0

Формат ур код правильно. –

+0

@BindiyaPatoliya сейчас я думаю, вы можете проверить это ... – naCheex

+0

срочно, пожалуйста, помогите мне – naCheex

ответ

1

Используйте это слово функции нажмите загрузки в вашем сохранении функции:

  // Upload the goal image to the uploads directory, resize the image, then upload the resized version 
      $goal_image_file = wp_upload_bits($_FILES['post_media']['name'], null, wp_remote_get($_FILES['post_media']['tmp_name'])); 

      // Set post meta about this image. Need the comment ID and need the path. 
      if(false == $goal_image_file['error']) { 

       // Since we've already added the key for this, we'll just update it with the file. 
       update_post_meta($post_id, 'umb_file', $goal_image_file['url']); 

      } 
+0

Я пробовал это, нет файлов в каталоге загрузки. – naCheex

+0

'post_media' - это имя тега ввода? (в моем случае это было бы% 1 $ s)? – naCheex

Смежные вопросы