how to grab first link in post… and of course call it

Two possibilities: Use the the_content-filter, or just call it in your template.

You can just throw the plugin in your folder, or add one (or both) function(s) in your themes functions.php file. The filter triggers only for the post format link, while the template tag can be used more universal – in the loop.

As a plugin

<?php
! defined( 'ABSPATH' ) AND exit;
/* Plugin Name: (#16365) »kaiser« Get 1st link inside the content */

// As an public API function
function wpse16365_get_content_link( $content = false, $echo = false )
{
if ( ! in_the_loop() )
    return;

    // allows using this function also for excerpts
    ! $content AND $content = get_the_content();

    $content = preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $content, $links );
    $content = $links[1][0];
    $content = make_clickable( $content );

    // if you set the 2nd arg to true, you'll echo the output, else just return for later usage
    $echo AND print $content;

    return $content;
}

// As a the_content-filter Callback
function wpse16365_get_content_link_cb( $content )
{
    if ( 'link' !== get_post_format() )
        return $content;

    $content = preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $content, $links );
    $content = $links[1][0];

    return make_clickable( $content );
}
add_filter( 'the_content', 'wpse16365_get_content_link_cb' );

This function should answer your Q. It’s tested and works fine.

Leave a Comment