Using WordPress ‘do_enclose()’ PHP function

The do_enclose() WordPress PHP function checks content for video and audio links and adds them as enclosures. It does not add enclosures that have already been added and will remove enclosures that are no longer in the post. This function is usually called during pingbacks and trackbacks.

Usage

Here’s a basic use case for do_enclose():

$content = "Check out this cool video: https://www.youtube.com/watch?v=dQw4w9WgXcQ";
$post_id = 123;
do_enclose($content, $post_id);

In this example, the do_enclose() function checks the $content string for any video or audio links and adds them as enclosures to the post with ID $post_id.

Parameters

  • $content (string|null) – Post content. If null, the post_content field from $post is used.
  • $post (int|WP_Post) – Post ID or post object.

More information

See WordPress Developer Resources: do_enclose
Please note that it’s important to use this function appropriately to avoid duplicate or missing enclosures in your posts.

Examples

Basic Use Case

$content = "Listen to this audio track: https://www.example.com/audio.mp3";
$post_id = 321;
do_enclose($content, $post_id);

This code checks the $content for audio links and adds them as enclosures to the post with ID $post_id.

With Null Content

$post_id = 456;
do_enclose(null, $post_id);

In this case, the post_content field from the post with ID $post_id is used.

Using a WP_Post Object

$post = get_post(789);
do_enclose(null, $post);

Here, a WP_Post object is used instead of a post ID. The post_content field from the $post object is used.

$content = "Check these out: https://www.example.com/video.mp4 https://www.example.com/audio.mp3";
$post_id = 654;
do_enclose($content, $post_id);

In this example, the function checks for multiple media links in the $content and adds each of them as an enclosure to the post with ID $post_id.

$content = "There are no media links in this content.";
$post_id = 987;
do_enclose($content, $post_id);

If there are no media links in the $content, this function doesn’t add any enclosures to the post with ID $post_id.