Plugin to automatically change anchor text of urls to the destinations title?

Say I link to http://www.glumbo.com on one of my posts. I want wordpress to automatically change the anchor text of the link to glumbo.com’s title. How can I do this?

Related posts

Leave a Reply

2 comments

  1. Decided to entertain the idea. Adapted from my snippet that changes anchors to collapsed domain names. Little too verbose, but seems to work.

    add_filter( 'the_content', 'anchors_to_page_titles' );
    
    function anchors_to_page_titles( $content ) {
    
        preg_match_all( '/<a.*?href="(.*?)".*?>(.*?)</a>/', $content, $matches );
        array_shift( $matches );
    
        foreach( $matches[0] as $key => $url ) {
    
        $anchor = $matches[1][$key];
    
        if( $url == $anchor ) {
    
            $transient_key = 'page_title_'.md5($url);
            $anchor = get_transient($transient_key);
    
            if( !$anchor ) {
    
                $response = wp_remote_request($url);
                $body = wp_remote_retrieve_body($response);
                $pattern = '/title>(.*?)</';
                $title = array();
                preg_match( $pattern, $body, $title);
    
                if( !empty( $title ) ) {
    
                    $title = $title[1];
                    $anchor = $title;
                    set_transient( $transient_key, $anchor, 60*60*24 );
                }
                else {
                    $anchor = $url;
                    set_transient( $transient_key, $anchor, 60*60 );
                }
            }
    
            $content = str_replace( ">{$url}</a>", ">{$anchor}</a>", $content );
        }
    
        }
    
        return $content;
    }
    

    PS maybe it would make sense to modify post on save rather than filtering on display… Well, as per my comment I don’t think page titles are good for this anyway.