登录 用户中心() [退出] 后台管理 注册
   
您的位置: 首页 >> SoftHub关联区 >> 主题: 获取WordPress文章的第一个链接[转贴信代码修复]     [回主站]     [分站链接]
获取WordPress文章的第一个链接[转贴信代码修复]
clq
浏览(309) - 2018-06-13 17:52:35 发表 编辑

关键字: WordPress

[2020-04-28 17:48:08 最后更新]
获取WordPress文章的第一个链接[转贴信代码修复]

https://www.wpdaxue.com/get-the-first-link-in-post.html

WordPress文章格式中有一种是链接,用来快速分享一个链接,如果我们可以将文章的这个链接自动链接到这篇文章的标题中,远比在文章内容中直接显示这个链接来的完美。将下面的代码添加到当前主题的 functions.php 中:



    

function get_content_link( $content = false, $echo = false )
{
    if ( $content === false )
        $content = get_the_content();
 
    $content = preg_match_all( '/hrefs*=s*["']([^"']+)/', $content, $links );
    $content = $links[1][0];
 
    if ( empty($content) ) {
        $content = false;
    }
 
    return $content;
}

然后你可以类似下面的代码来为标题添加这个链接:
    

<h2><a href="<?php echo get_content_link( get_the_content() ); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<a href="<?php the_permalink(); ?>">Comment »</a>

参考资料:http://wp-snippets.com/get-the-first-link-in-post/


clq  2018-06-13 17:53:26 发表 编辑

这篇文章不知何原因关键代码其实是错误的,应该为

    //$content = preg_match_all( '/hrefs*=s*["']([^"']+)/', $content, $links ); //奇怪网上的这个代码居然是错误的,要写单引号的转义符才行
    $content = preg_match_all( '/hrefs*=s*["\']([^"\']+)/', $content, $links );



总数:1 页次:1/1 首页 尾页  
总数:1 页次:1/1 首页 尾页  


所在合集/目录



发表评论:
文本/html模式切换 插入图片 文本/html模式切换


附件:



NEWBT官方QQ群1: 276678893
可求档连环画,漫画;询问文本处理大师等软件使用技巧;求档softhub软件下载及使用技巧.
但不可"开车",严禁国家敏感话题,不可求档涉及版权的文档软件.
验证问题说明申请入群原因即可.

Copyright © 2005-2020 clq, All Rights Reserved
版权所有
桂ICP备15002303号-1