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:
- Add this code to your theme’s functions.php file or in a site-specific plugin.
- 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!
Hi, thanks for this useful post, I did copy paste the code to function.php
now what code I need to call this function??
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/