Using WordPress ‘get_url_in_content()’ PHP function

The get_url_in_content() WordPress PHP function extracts and returns the first URL from the passed content.

Usage

get_url_in_content( $content );

Example:

$content = "Check out my favorite website: https://www.example.com!";
$url = get_url_in_content( $content );
echo $url; // Output: https://www.example.com

Parameters

  • $content (string) (Required): A string which might contain a URL.

More information

See WordPress Developer Resources: get_url_in_content()

Examples

Extract URL from a blog post

This example extracts the first URL from a blog post’s content.

$post_content = "This is my blog post. Visit my portfolio at https://www.myportfolio.com.";
$first_url = get_url_in_content( $post_content );
echo $first_url; // Output: https://www.myportfolio.com

Extract URL from a block of HTML

This example extracts the first URL from a block of HTML content.

$html_content = "<p>Find more information on <a href='https://www.example.org'>example.org</a>.</p>";
$first_url = get_url_in_content( $html_content );
echo $first_url; // Output: https://www.example.org

Extract URL from a string with multiple URLs

This example extracts the first URL from a string containing multiple URLs.

$multiple_urls = "Check these websites: https://site-a.com, https://site-b.com, and https://site-c.com.";
$first_url = get_url_in_content( $multiple_urls );
echo $first_url; // Output: https://site-a.com

Display message when no URL is found

This example displays a message when no URL is found in the content.

$content_without_url = "This content has no URL.";
$found_url = get_url_in_content( $content_without_url );

if ( $found_url ) {
    echo $found_url;
} else {
    echo "No URL found in the content.";
}

Extract URL from a custom field

This example extracts the first URL from a custom field called “resources”.

$custom_field_content = get_post_meta( $post->ID, 'resources', true );
$first_url = get_url_in_content( $custom_field_content );
echo $first_url; // Output: First URL found in the custom field "resources"