do_enclose()


WordPressのdo_enclose()関数は、指定された投稿に含まれるメディアファイル(例:オーディオ、ビデオ)を検出し、それらのファイルを囲むためのリンクを生成するために使用されます。

構文

do_enclose( string $content, int $post_id );

引数の説明:

  • $content (string) — 投稿のコンテンツを指定します。
  • $post_id (int) — メディアファイルを検出する投稿のIDを指定します。

例1: 基本的な使用法

この例では、投稿IDを指定してdo_enclose()関数を使用します。

<?php do_enclose(get_the_content(), get_the_ID()); ?>

例2: カスタム投稿IDでの使用

特定の投稿IDに対してdo_enclose()を適用します。

<?php do_enclose(get_post_field('post_content', 456), 456); ?>

例3: フィルターフックとの併用

the_contentフィルターフックと組み合わせて使用します。

<?php add_filter('the_content', function($content) { return do_enclose($content, get_the_ID()); }); ?>

例4: ショートコード内での使用

ショートコード内でdo_enclose()を利用します。

<?php add_shortcode('custom_enclose', function($atts) { return do_enclose(get_the_content(), get_the_ID()); }); ?>

例5: 特定のメディアタイプを対象にする

特定のメディアタイプ(例:MP3ファイル)を対象にします。

<?php do_enclose(preg_replace('/\.mp3/', '', get_the_content()), get_the_ID()); ?>

例6: 複数の投稿に適用

複数の投稿に対してdo_enclose()をループで適用します。

<?php $posts = get_posts(array('numberposts' => 5)); foreach ($posts as $post) { do_enclose($post->post_content, $post->ID); } ?>

例7: カスタムクエリでの使用

カスタムクエリを使用してdo_enclose()を適用します。

<?php $query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3)); while ($query->have_posts()) { $query->the_post(); do_enclose(get_the_content(), get_the_ID()); } ?>

例8: エンクロージャーリンクのカスタマイズ

エンクロージャーリンクの出力をカスタマイズします。

<?php $enclosures = do_enclose(get_the_content(), get_the_ID()); if (!empty($enclosures)) { foreach ($enclosures as $enclosure) { echo '<a href="' . esc_url($enclosure) . '">メディアファイル</a>'; } } ?>

注意点

  • do_enclose()は、投稿内のメディアファイルを自動的に検出しますが、すべてのメディアタイプをサポートしているわけではありません。
  • この関数は、主にRSSフィードでの使用を想定しています。

関連機能: