Skip to content

Instantly share code, notes, and snippets.

@yuis-ice
Last active July 27, 2017 00:10
Show Gist options
  • Save yuis-ice/cebda864db1469a787e9f5481e112b1d to your computer and use it in GitHub Desktop.
Save yuis-ice/cebda864db1469a787e9f5481e112b1d to your computer and use it in GitHub Desktop.
Displayed link with link-destination-title for add_shortcode.

wp get title

Displayed link with link-destination-title for add_shortcode.

<?php


function get_title($attr){
  $url=$attr[0] ;

  $html = file_get_contents($url);

  $doc = new DOMDocument();

  libxml_use_internal_errors(TRUE);

  if(!empty($html)){

  	$doc->loadHTML($html);
  	libxml_clear_errors();

  	$xpath = new DOMXPath($doc);

  	$xpath_row = $xpath->query('//title') ;

  	if($xpath_row->length > 0 && $xpath_row->length < 2){
  		foreach($xpath_row as $row){
  			$output=$row->nodeValue . "\n";
  			// return $row->nodeValue . "<br/>";
  		}
  	}

    if($output==false){
      $output=$url ;
    }

    return "<a href=\"{$url}\"" . '  target="_blank" rel="nofollow"  ' . ">{$output}</a>";

  }
}

add_shortcode('get_title', 'get_title') ;


 ?>

usage

Add this PHPcode to child-theme's functions.php.

Add shortcode in wordpress html editor. [get_title "https://stackoverflow.com"]

view on brawzer. Then, link is displayed with link-destination-title. Stack Overflow - Where Developers Learn, Share, & Build Careers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment