<?php
/*
Plugin Name: q-wp-linkreplace
Plugin URI: http://tonosdegris.com/
Description: Replace text in posts with links from wp_links
Version: 1.0
Author: Christian Soto
Author URI: http://tonosdegris.com/
*/ 

/*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

function wplink_replace($text)
{
    
//Get database connection object, and name of links table;
    
global $wpdb$tablelinks;

    
//Config variables --  change to suit you need! Defaults point to wordpress' links table
    //Field required: name, url.  Leave url, target and description blank to ommit them
    
$tablename $tablelinks;
    
$name_column "link_name";
    
$url_column "link_url";
    
$target_column "link_target";
    
$description_column "link_description";
    
    
//For each link, replace the name of the link within the post with the link
    
foreach ( $wpdb->get_results("select $name_column as link_name".($url_column?", $url_column as link_url":"").($target_column?", $target_column as link_target":"").($description_column?", $description_column as link_description":"")." from $tablename") as $row) {
        
$replace "<a href=\"".$row->link_url."\" target=\"".$row->link_target."\" title=\"".$row->link_description."\">".$row->link_name."</a>";
        
$text preg_replace '#(<a\s.*>.*'.$row->link_name.'.*</a>)|('.$row->link_name.')#Uie'"'$1'?stripslashes('$1'):'".$replace."'"$text);
    }
    
    
//return output text;
    
return trim($text);
}

add_filter('the_content''wplink_replace');
?>