Using WordPress ‘enclosure_links’ PHP filter

The enclosure_links WordPress PHP filter lets you modify the list of enclosure links before it is queried in the database.

Usage

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

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

Parameters

  • $post_links (string[]): An array of enclosure links.
  • $post_id (int): Post ID.

More information

See WordPress Developer Resources: enclosure_links

Examples

Remove a specific enclosure link from the list before saving to the postmeta.

add_filter('enclosure_links', 'remove_specific_enclosure_link', 10, 2);

function remove_specific_enclosure_link($post_links, $post_id) {
    $link_to_remove = 'https://example.com/bad-link.mp3';
    $post_links = array_diff($post_links, [$link_to_remove]);
    return $post_links;
}

Add a new enclosure link to the list before saving to the postmeta.

add_filter('enclosure_links', 'add_new_enclosure_link', 10, 2);

function add_new_enclosure_link($post_links, $post_id) {
    $new_link = 'https://example.com/new-link.mp3';
    $post_links[] = $new_link;
    return $post_links;
}

Replace the domain name of all enclosure links before saving to the postmeta.

add_filter('enclosure_links', 'modify_enclosure_links', 10, 2);

function modify_enclosure_links($post_links, $post_id) {
    $old_domain = 'https://old.example.com';
    $new_domain = 'https://new.example.com';

    $post_links = array_map(function ($link) use ($old_domain, $new_domain) {
        return str_replace($old_domain, $new_domain, $link);
    }, $post_links);

    return $post_links;
}

Remove all enclosure links from the list before saving to the postmeta.

add_filter('enclosure_links', 'remove_all_enclosure_links', 10, 2);

function remove_all_enclosure_links($post_links, $post_id) {
    return [];
}

Keep only enclosure links with a specific file extension before saving to the postmeta.

add_filter('enclosure_links', 'filter_enclosure_links_by_extension', 10, 2);

function filter_enclosure_links_by_extension($post_links, $post_id) {
    $allowed_extension = '.mp3';
    $post_links = array_filter($post_links, function ($link) use ($allowed_extension) {
        return substr($link, -strlen($allowed_extension)) === $allowed_extension;
    });

    return $post_links;
}