WordPress网站添加动态友链的代码分享?
先解释一下,这个【动态友链】主要是我为了方便取的名字,估计没有人知道这个功能叫什么,也没有专门的称呼,所以我们给他命名为动态友情链接;最近看到很多wp程序的博客首页都有这么一个模块,显示的是最近评论了网站访客的友情链接,这个版块展示效果如下所示;
或者是这样的,
如果你发表了评论,你的网站链接就会展示在第一个位置,动态变化的,又是在首页显示,所以我给他取个名字叫动态友链,类似于抢排名的道理,这样可以明显增加自己网站的人气和访问深度,访客的行为和粘性都会提高很多的,感觉不错我就自己写代码做了一个放在我的wordpress建站吧上。
不清楚这个功能是不是有插件可以实现,或者其他的方法实现,反正我自己尝试着用不入流的代码水平勉强给写出来了,这里分享给大家吧!
首先在主题发function.php 文件中增加这段代码,是获取wp_comments评论表里面的评论者信息,判断的是按照url分组查询的结果显示前面最新的12条记录,代码如下;
//2018年11月14日00:05:24添加【动态友链】,WordPress建站吧
function getvisitors() {
global $wpdb;
$query="select * from `wp_comments` where `comment_approved`=1 group by `comment_author_url`
order by comment_ID desc limit 12";
$sql = $wpdb -> get_results($query, ARRAY_A);
//print_r($sql);
//新添加2018年11月13日23:55:41
foreach($sql as $vales){
echo "<li><img src='https://www.zouaw.com/wp-content/uploads/2018/11/timg-1.gif'>
<a target='_blank' rel='nofollow' href=".$vales["comment_author_url"].">".$vales["comment_author"]."</a>
</li>";
}
}
然后再首页index.php需要展示版块内容的地方添加上如下代码,样式表估计需要修改成适应自己模板的;css代码也写在了里面;
<div class="vistor">
<style>
.vistor{width:100%;margin-bottom:30px;height:auto!important;background:#fff;
border:1px solid #f5f9ff;text-align:center;color:#096cb2;
border:1px solid #eaeaea;border-radius:4px;}
.vistor p{padding-top:4px;font-size:16px;}
.vistor ul{margin-top:10px;margin-bottom:10px;font-size:13px;padding-bottom:40px;}
.vistor ul li{list-style:none;float:left;margin-left:0px;margin-bottom:10px;width:125px;
overflow:hidden;height:20px;text-align:left;}
.vistor ul li img{width:20px;height:20px;margin-left:2px;margin-right:2px;}
/*移动端想显示的话可以注销或者删除下面的这一行*/
@media (max-width:900px) {.vistor{display:none}}
</style>
<p>【动态友链】每评论一次你就会自动排第一位哦</p>
<ul>
<?php
//2018年11月13日23:17:58增加的,近期发布评论的访客信息友情链接版块;WordPress建站吧
getvisitors();
?>
</ul>
<div style="clear: both;display:block"> </div>
</div>
反正在我站点还是可以用的移动pc都兼容的。