如何在文件上载时添加自定义元值?

时间:2015-12-19 作者:Bhupathi Reddy NeverLie

我正在寻找一个选项,当用户上传附件时,将保存一个自定义元值。

假设我需要一个元键\\u example\\u meta\\u key,并希望将其元值保存为ex087659bh(这将是一个随机生成的数字,我可以处理)

问题是,我似乎找不到任何过滤器来在上传时添加自定义元值。

有一些教程介绍了如何在媒体编辑表单中添加字段,但我需要在上传文件时执行这些教程。

2 个回复
SO网友:jgraup

使用added_post_metaupdate_post_meta 使用$post_id. 有关扩展属性,请参见postthis 获取更多图像功能。

add_action(\'added_post_meta\', \'wpse_20151218_after_post_meta\', 10, 4);

function wpse_20151218_after_post_meta($meta_id, $post_id, $meta_key, $meta_value) {

    // _wp_attachment_metadata added
    if($meta_key === \'_wp_attachment_metadata\') {

        // Add Custom Field
        update_post_meta($post_id, \'_example_meta_key\', \'ex087659bh\');

        // _wp_attached_file
        // _wp_attachment_metadata (serialized)
        // _wp_attachment_image_alt
        // _example_meta_key

        $attachment_meta = get_post_meta($post_id);
    }
}

SO网友:Omar Tariq

正如@jgraup指出的那样。您可以使用过滤器wp_handle_upload. 最后的代码看起来像下面粘贴的东西。您可能只想使用两个挂钩中的一个,或者两个都用。

add_filter(\'wp_handle_upload_prefilter\', \'startOfWpHandleUpload\', 10, 2 );

function startOfWpHandleUpload( $file ) {

    /* Here you can access the following properties of the uploaded file
     * before it is processed by the wp_handle_upload function. 
     */

    /* Name of the uploaded file. */
    $file[\'name\'];
    /* MIME Type of the uploaded file. */
    $file[\'type\'];
    /* Temporary location of the stored file. */
    $file[\'tmp_name\'];
    /* "0" for no errror. Don\'t know what is for error. */
    $file[\'error\'];
    /* size in bytes of the uploaded file. */
    $file[\'size\'];

    return $file;
}

add_filter(\'wp_handle_upload\', \'endOfWpHandleUpload\', 10, 2 );

function endOfWpHandleUpload( $file, $type ) {

    /* Here you can access the following properties of the uploaded file
     * before it is processed by the wp_handle_upload function.
     */

    /* Absolute path of the file on the filesystem of the operating system. */
    $file[\'file\'];
    /* Public accessible URL of the file over the Internet. */
    $file[\'url\'];
    /* MIME type of the file. */
    $file[\'type\'];

    return $file;
}