Using WordPress ‘prepend_attachment’ PHP filter

The ‘prepend_attachment’ is a WordPress PHP filter that allows you to modify the attachment markup before it is added to the post content.

Usage

To use this filter, you need to create a function and hook it to the 'prepend_attachment' filter, like this:

function your_function_name( $attachment_markup ) {
    // Your code here
    return $attachment_markup;
}
add_filter( 'prepend_attachment', 'your_function_name' );

Parameters

  • $p (string): The attachment HTML output.

Examples

Add a custom CSS class to the attachment markup

function add_custom_class( $attachment_markup ) {
    return str_replace( '<a ', '<a class="custom-class" ', $attachment_markup );
}
add_filter( 'prepend_attachment', 'add_custom_class' );

This code adds a custom CSS class named “custom-class” to the attachment markup.

Wrap the attachment in a div

function wrap_attachment_div( $attachment_markup ) {
    return '<div class="attachment-wrapper">' . $attachment_markup . '</div>';
}
add_filter( 'prepend_attachment', 'wrap_attachment_div' );

This code wraps the attachment markup in a div with the class “attachment-wrapper”.

function add_download_link( $attachment_markup ) {
    $download_link = '<a href="' . wp_get_attachment_url() . '" download>Download</a>';
    return $attachment_markup . $download_link;
}
add_filter( 'prepend_attachment', 'add_download_link' );

This code adds a download link below the attachment markup.

function remove_attachment_link( $attachment_markup ) {
    return preg_replace( '/<a[^>]*>/', '', $attachment_markup );
}
add_filter( 'prepend_attachment', 'remove_attachment_link' );

This code removes the link from the attachment markup, leaving only the image.

Change the attachment markup to a responsive image

function responsive_attachment( $attachment_markup ) {
    $attachment_id = get_post_thumbnail_id();
    $srcset = wp_get_attachment_image_srcset( $attachment_id );
    return preg_replace( '/<img([^>]*)>/', '<img$1 srcset="' . $srcset . '">', $attachment_markup );
}
add_filter( 'prepend_attachment', 'responsive_attachment' );

This code changes the attachment markup to include the srcset attribute, making the image responsive.