Skip to content

Instantly share code, notes, and snippets.

@SitesByYogi
Last active September 6, 2024 19:38
Show Gist options
  • Save SitesByYogi/8d4c9ce93c8653e16ccffa81c5320f75 to your computer and use it in GitHub Desktop.
Save SitesByYogi/8d4c9ce93c8653e16ccffa81c5320f75 to your computer and use it in GitHub Desktop.
Adds new fields to audio player
<?php
// Hook into the attachment fields
add_filter('attachment_fields_to_edit', 'add_custom_audio_fields', 10, 2);
add_filter('attachment_fields_to_save', 'save_custom_audio_fields', 10, 2);
// Function to add custom fields
function add_custom_audio_fields($form_fields, $post) {
// Only show these fields for audio files
if ($post->post_mime_type == 'audio/mpeg' || $post->post_mime_type == 'audio/wav' || $post->post_mime_type == 'audio/ogg') {
// Record Label field
$form_fields['record_label'] = [
'label' => 'Record Label',
'input' => 'text',
'value' => get_post_meta($post->ID, 'record_label', true),
'helps' => 'Enter the record label of the audio file.'
];
// Artist field
$form_fields['artist'] = [
'label' => 'Artist',
'input' => 'text',
'value' => get_post_meta($post->ID, 'artist', true),
'helps' => 'Enter the artist name of the audio file.'
];
// Year field
$form_fields['year'] = [
'label' => 'Year',
'input' => 'text',
'value' => get_post_meta($post->ID, 'year', true),
'helps' => 'Enter the release year of the audio file.'
];
}
return $form_fields;
}
// Function to save custom fields
function save_custom_audio_fields($post, $attachment) {
if (isset($attachment['record_label'])) {
update_post_meta($post['ID'], 'record_label', sanitize_text_field($attachment['record_label']));
}
if (isset($attachment['artist'])) {
update_post_meta($post['ID'], 'artist', sanitize_text_field($attachment['artist']));
}
if (isset($attachment['year'])) {
update_post_meta($post['ID'], 'year', sanitize_text_field($attachment['year']));
}
return $post;
}
// Add the shortcode to display audio metadata
function display_audio_meta_shortcode($atts) {
// Fetch current post ID
$post_id = get_the_ID();
// Fetch audio metadata
$record_label = get_post_meta($post_id, 'record_label', true);
$artist = get_post_meta($post_id, 'artist', true);
$year = get_post_meta($post_id, 'year', true);
// Start output buffering
ob_start();
// Check if there's any audio metadata available
if ($record_label || $artist || $year) {
echo '<div class="audio-meta">';
// Display Record Label
if ($record_label) {
echo '<p><strong>Record Label:</strong> ' . esc_html($record_label) . '</p>';
}
// Display Artist
if ($artist) {
echo '<p><strong>Artist:</strong> ' . esc_html($artist) . '</p>';
}
// Display Year
if ($year) {
echo '<p><strong>Year:</strong> ' . esc_html($year) . '</p>';
}
echo '</div>';
}
// Return the buffered output
return ob_get_clean();
}
add_shortcode('audio_meta', 'display_audio_meta_shortcode');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment