How to get the ID of an item in an audio playlist?

We don’t have an explicit filter for the data array so here are two workarounds that you might give a try:

Approach #1 – As meta data

We can add attachment_id to the meta data for each playlist item, via the wp_get_attachment_metadata filter, but first we have to register it via the
wp_get_attachment_id3_keys filter.

Here’s an example:

// Add 'attachment_id' as an id3 meta key
add_filter( 'wp_get_attachment_id3_keys', $callback_id3 = function( $fields ) 
{
    $fields['attachment_id'] = 'attachment_id';
    return $fields;
} );

// Add ?attachment_id=123 to the url
add_filter( 'wp_get_attachment_metadata', $callback_metadata = function ( $data, $post_id )
{
    $data['attachment_id'] = (int) $post_id;
    return $data;
}, 10, 2 );

// Output from playlist shortcode
$output = wp_playlist_shortcode( $atts, $content );

// Remove our filter callback
remove_filter( 'wp_get_attachment_url', $callback_metadata );
remove_filter( 'wp_get_attachment_id3_keys', $callback_id3 );

Approach #2 – As query string

Alternatively we can add the ?attachment_id=123 query string to the attachments url, via the wp_get_attachment_url filter.

Here’s an example:

// Add our filter callback to add ?attachment_id=123 to the url
add_filter( 'wp_get_attachment_url', $callback = function ( $url, $post_id )
{
    return add_query_arg( 'attachment_id', (int) $post_id, $url );
}, 10, 2 );

// Output from playlist shortcode
$output = wp_playlist_shortcode( $atts, $content );

// Remove our filter callback
remove_filter( 'wp_get_attachment_url', $callback );       

Hope it helps!

Leave a Comment

error code: 523