Using WordPress ‘get_enclosed()’ PHP function

The get_enclosed WordPress PHP function retrieves enclosures already enclosed for a post.

Usage

get_enclosed($post_id);

Example:
Input:

$post_id = 123;
$enclosures = get_enclosed($post_id);

Output:

Array of enclosures

Parameters

  • $post_id (int) – Required. The Post ID you want to retrieve enclosures for.

More information

See WordPress Developer Resources: get_enclosed

Examples

Retrieve and display enclosures for a post

$post_id = 123;
$enclosures = get_enclosed($post_id);

foreach ($enclosures as $enclosure) {
    echo 'Enclosure: ' . $enclosure . '<br>';
}

Create a list of enclosures for a post

$post_id = 456;
$enclosures = get_enclosed($post_id);

echo '<ul>';
foreach ($enclosures as $enclosure) {
    echo '<li>' . $enclosure . '</li>';
}
echo '</ul>';

Retrieve enclosures and count them for a post

$post_id = 789;
$enclosures = get_enclosed($post_id);
$enclosure_count = count($enclosures);

echo 'Number of enclosures: ' . $enclosure_count;

Check if a post has any enclosures

$post_id = 111;
$enclosures = get_enclosed($post_id);

if (!empty($enclosures)) {
    echo 'This post has enclosures!';
} else {
    echo 'This post has no enclosures.';
}

Retrieve and display enclosures for all posts in a loop

// Get all published posts
$posts = get_posts(array('post_status' => 'publish'));

foreach ($posts as $post) {
    echo 'Post ID: ' . $post->ID . '<br>';
    $enclosures = get_enclosed($post->ID);

    if (!empty($enclosures)) {
        echo 'Enclosures:<br>';
        foreach ($enclosures as $enclosure) {
            echo ' - ' . $enclosure . '<br>';
        }
    } else {
        echo 'No enclosures for this post.<br>';
    }
    echo '<br>';
}