wordpress技巧:获取文章的第一个链接地址


前面我们讲了wordpress获取文章中的第一张图片的方法,接下来我为大家介绍如何在wordpress中获取文章的第一个链接,方法也很简单,将如下函数添加至你主题的functions.php文件中,如何在模板文件的循环(Loop)中调用该函数即可:

  1. function get_link_url() {
  2. $content = get_the_content();
  3. $has_url = get_url_in_content( $content );
  4.  
  5. return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
  6. }

方法解析

以上方法主要用到了 wordpress get_url_in_content()方法:
方法使用:

  1. get_url_in_content ( $content )

参数
(string) $content 包含url的文章内容
返回值
(string) 返回匹配的第一个URL
源代码
该函数位于wp-includes/formatting.php文件的第3425行
源代码如下:

  1. function get_url_in_content( $content ) {
  2. if ( empty( $content ) )
  3. return '';
  4.  
  5. if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) )
  6. return esc_url_raw( $matches[2] );
  7.  
  8. return false;
  9. }