我希望在通过自定义字段上传时获取音频文件的持续时间,并将其保存在后置元数据中。
答案 0 :(得分:1)
WordPress使用ID3 library内置音频功能,可以帮助您实现这一目标。
首先,您将使用acf/save_post挂钩挂钩ACF。然后,您将使用WP函数wp_read_audio_metadata()来获取音频文件的元数据。最后,您将使用update_post_meta()函数将数据保存到帖子中。像这样:
function save_audio_duration($post_id) {
// Get the WP Uploads Directory (where ACF saves files)
$uploads = wp_upload_dir();
$uploads_dir = ( $uploads['baseurl'] . $uploads['subdir'] );
// Get the file name from ACF & create the file string
$file_obj = get_field('audio_file', $post_id);
$file = $uploads_dir . '/' . $file_obj['filename'];
// Use the wp_read_audio_metadata() function to get data
$metadata = wp_read_audio_metadata( $file );
// Save the file length to the post meta
update_post_meta($post_id, 'audio_length', $metadata['length']);
}
// Will execute AFTER post has been saved (change "20" to "1" to execute before)
add_action('acf/save_post', 'save_audio_duration', 20);
注意: $metadata['length']
将以秒为单位返回时间,而$metadata['length_formatted']
将以格式化字符串返回时间。
注意x2:如果在执行此操作的操作中将“20”更改为“1”,则在将字段保存到帖子之前,您需要更改get_field()
功能到$_POST['audio_file']
,因为在ACF将字段保存到数据库之前将执行该功能。
答案 1 :(得分:1)
我为您的vídeos修改了一些不错的代码:
function save_video_duration($post_id) {
// Get the file name from ACF & create the file string
$file_obj = get_field('video_file', $post_id);
// Get the WP Uploads Directory (where ACF saves files)
$file = get_attached_file( attachment_url_to_postid( get_field('video_file', $post_id) ) );
// Use the wp_read_audio_metadata() function to get data
$metadata = wp_read_video_metadata($file);
// Save the file length to the post meta
update_post_meta($post_id, 'video_file_length', $metadata['length']);
}
// Will execute AFTER post has been saved (change "20" to "1" to execute before)
add_action('acf/save_post', 'save_video_duration', 20);
谢谢