X

How To Get the First Link in a Post

Snippets by IsItWP

Are you looking for a way to get the first link in a post? This snippet will get the URL in the post meta (if it exists) or the first link found in the post content. As a fallback, it will get the post permalink if no URL is found in the post, which can be useful for the “link” post format.

Instructions:

  1. Add this code to your theme’s functions.php file or in a site-specific plugin.
  2. Call the function in The Loop within a template file when you need to get the first link in the post.
function get_link_url() {
    $content = get_the_content();
    $has_url = get_url_in_content( $content );

    return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 9 Best SEO Tools to Grow Your Website Traffic, FAST!

Comments   Leave a Reply

  1. Hi, thanks for this useful post, I did copy paste the code to function.php
    now what code I need to call this function??

    1. You would need to add get_link_url(); in The Loop within a template file. You may want to check out: https://www.isitwp.com/the-ultimate-guide-to-the-wordpress-loop/

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!