Using WordPress ‘get_enclosed’ PHP filter

The get_enclosed WordPress PHP filter allows you to modify the list of enclosures associated with a specific post.

Usage

add_filter('get_enclosed', 'your_custom_function', 10, 2);

function your_custom_function($pung, $post_id) {
    // your custom code here
    return $pung;
}

Parameters

  • $pung (string[]): Array of enclosures for the given post.
  • $post_id (int): Post ID.

More information

See WordPress Developer Resources: get_enclosed

Examples

Remove a specific enclosure from the list

add_filter('get_enclosed', 'remove_specific_enclosure', 10, 2);

function remove_specific_enclosure($pung, $post_id) {
    $enclosure_to_remove = 'http://example.com/somefile.mp3';
    if (($key = array_search($enclosure_to_remove, $pung)) !== false) {
        unset($pung[$key]);
    }
    return $pung;
}

Add an enclosure to the list

add_filter('get_enclosed', 'add_new_enclosure', 10, 2);

function add_new_enclosure($pung, $post_id) {
    $new_enclosure = 'http://example.com/newfile.mp4';
    $pung[] = $new_enclosure;
    return $pung;
}

Replace an existing enclosure with a new one

add_filter('get_enclosed', 'replace_enclosure', 10, 2);

function replace_enclosure($pung, $post_id) {
    $old_enclosure = 'http://example.com/oldfile.mp3';
    $new_enclosure = 'http://example.com/newfile.mp3';
    if (($key = array_search($old_enclosure, $pung)) !== false) {
        $pung[$key] = $new_enclosure;
    }
    return $pung;
}

Remove all enclosures for a specific post

add_filter('get_enclosed', 'remove_all_enclosures', 10, 2);

function remove_all_enclosures($pung, $post_id) {
    if ($post_id == 123) {
        $pung = [];
    }
    return $pung;
}

Remove enclosures with a specific file extension

add_filter('get_enclosed', 'remove_enclosures_by_extension', 10, 2);

function remove_enclosures_by_extension($pung, $post_id) {
    $extension_to_remove = '.mp4';
    $pung = array_filter($pung, function($enclosure) use ($extension_to_remove) {
        return (substr($enclosure, -strlen($extension_to_remove)) !== $extension_to_remove);
    });
    return $pung;
}