我有一个名为[‘notifications’]的自定义帖子类型, 其中[[notifications]]中的所有帖子都有一个名为[‘attachment’]的自定义字段。
- 我希望用户从前端将附件上传到库中
- 如果上传成功
- 获取附件的文件名
- 然后通过其ID更新自定义帖子类型[‘notifications’]中的帖子
- 将帖子中的自定义字段[‘attachment’]更新为文件名
自定义字段的meta_key为[‘_ct_text_57fc8ec4573cd’]
这就是我到目前为止
对于前端
<?php
if (isset($_POST['upload'])) {
if (!empty($_FILES)) {
$file = $_FILES['file'];
$attachment_id = upload_user_file($file);
}
}
?>
<form action="" enctype="multipart/form-data" method="post">
<input name="file" type="file">
</form>
内置函数
function upload_user_file($file = array()) {
require_once(ABSPATH. 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
return false;
} else {
$filename = $file_return['file'];
$post_ID_attachment = 33;
$attachment = array('post_mime_type' => $file_return['type'], 'post_title' => $post_ID_attachment, 'post_content' => '', 'post_status' => 'inherit', 'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH. 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
if (0 < intval($attachment_id)) {
return $attachment_id;
}
/* UPDATE ATTACHMENT BELOW*/
update_post_meta($post_ID_attachment, '_ct_text_57fc8ec4573cd', $filename);
}
return false;
}
不知道我是否做对了。上面的代码已成功插入附件, 但未更新帖子类型[‘notifications’]中的自定义字段
#1
在update_post_meta查询之前, 你的函数中有一个return语句。尝试以下代码:
function upload_user_file($file = array()) {
require_once(ABSPATH. 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
return false;
} else {
$filename = $file_return['file'];
$post_ID_attachment = 33;
$attachment = array('post_mime_type' => $file_return['type'], 'post_title' => $post_ID_attachment, 'post_content' => '', 'post_status' => 'inherit', 'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH. 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
/* UPDATE ATTACHMENT BELOW*/
update_post_meta($post_ID_attachment, '_ct_text_57fc8ec4573cd', $filename);
if (0 < intval($attachment_id)) {
return $attachment_id;
}
}
return false;
}
另外我不确定你的代码中是否需要这些require_once-s, 因为在function.php中需要加载所有内容。
评论前必须登录!
注册