我有一个名为[' notifications']的自定义帖子类型,其中包含一个名为[' attachment']的自定义字段,用于[' notifications']中的所有帖子。
自定义字段的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>
INSIDE FUNCTIONS.PHP
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;
}
不确定我是否正确操作。 上面的代码成功插入了附件,但它没有更新帖子类型中的自定义字段[&#39; notifications&#39;]
答案 0 :(得分:0)
在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
中,所有内容都应该加载。