wp_extract_urls()


WordPressの関数wp_extract_urls()は、指定された文字列からすべてのURLを抽出するために使用されます。この関数は、投稿内容や任意のテキストからURLリストを取得したい場合に便利です。

シンタックス

array wp_extract_urls( string $content )
  • $content (string) — URLを抽出する対象となる文字列。

戻り値:

  • 指定された文字列に含まれるすべてのURLを含む配列を返します。

使用例

例1: 投稿内容からURLを取得

指定された投稿の内容からすべてのURLを取得する例です。

<?php
$content = get_the_content();
$urls = wp_extract_urls($content);
print_r($urls);
?>

例2: 固定ページの内容からURLを取得

固定ページの内容に含まれるすべてのURLを取得します。

<?php
$content = apply_filters('the_content', get_post_field('post_content', get_the_ID()));
$urls = wp_extract_urls($content);
foreach ($urls as $url) {
    echo $url . '<br>';
}
?>

例3: カスタムフィールドの値からURLを抽出

カスタムフィールドに含まれるURLを取得します。

<?php
$content = get_post_meta(get_the_ID(), 'custom_field_key', true);
$urls = wp_extract_urls($content);
?>

例4: コメント内容からURLを取得

コメント内容に含まれるURLを抽出します。

<?php
$comments = get_comments(array('post_id' => get_the_ID()));
foreach ($comments as $comment) {
    $urls = wp_extract_urls($comment->comment_content);
    print_r($urls);
}
?>

例5: ウィジェット設定からURLを取得

ウィジェット設定に保存されているURLを抽出します。

<?php
$widget_content = get_option('widget_text');
foreach ($widget_content as $widget) {
    if (isset($widget['text'])) {
        $urls = wp_extract_urls($widget['text']);
        print_r($urls);
    }
}
?>

注意事項

  • この関数は、正しいフォーマットのURLのみを抽出します。フォーマットが不正な場合は無視されます。
  • 抽出結果は配列として返されるため、必要に応じて追加の処理を行うことが可能です。

関連機能: