制作WordPress侧边栏“热门文章”小工具,并集成在主题中

2023-05-0222:49:22网站建设与开发Comments982 views字数 1679阅读模式

“热门文章”的“热门”指的是一段时间内评论数多的文章,用本方法实现的小工具可以在后台随意开启,想用就用,不想用也不用删除代码。现在直接提供教程:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

一、“热门文章”小工具相关代码

新建一个php文件,命名为widget_hotposts.php,输入以下内容并以utf-8编码格式保存。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

<ul class="widget-container"><li class="widget"> <h3 class="widgettitle">热门文章</h3> <ul> <?php if(function_exists('most_comm_posts')) most_comm_posts(60,5); ?> </ul> </li> </ul>文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

注意: 1、上面代码的most_comm_posts(60,5);,5表示显示5篇随机文章,60表示调用60天内热门文章,你可以修改为你需要的文章数; 2、上面代码的相关css选择器(class="widget-container"、class="widget")需要改为与你的主题相适合的选择器名。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

二、定义相关函数并向WordPress后台调用“热门文章”小工具

将上面的widget_hotposts.php文件放在你的主题路径下,如我的是放在主题的/lib/widgets/下,那么就在主题的fountions.php的最后一个 ?>前添加如下代码:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

//边栏热门文章 Devework.com function most_comm_posts($days=30, $nums=5) { global $wpdb; $today = date("Y-m-d H:i:s"); $daysago = date( "Y-m-d H:i:s", strtotime($today) - ($days * 24 * 60 * 60) ); $result = $wpdb->get_results("SELECT comment_count, ID, post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' ORDER BY comment_count DESC LIMIT 0 , $nums"); $output = ''; if(empty($result)) { $output = '<li>None data.</li>'; } else { foreach ($result as $topten) { $postid = $topten->ID; $title = $topten->post_title; $commentcount = $topten->comment_count; if ($commentcount != 0) { $output .= '<li><a target="_blank" href="'.get_permalink($postid).'" title="'.$title.'">'.$title.'</a></li>'; } } } echo $output; } //后台调用 Devework.com class widget_most_comm extends WP_Widget{ function widget_most_comm(){ $widget_options = array('classname'=>'set_contact','description'=>'本站主题目前自带的热门文章小工具'); $this->WP_Widget(false,'Devework.com热门文章',$widget_options); } function widget($instance){ include(TEMPLATEPATH .'/lib/widgets/widget_hotposts.php'); }} add_action('widgets_init',create_function('', 'return register_widget("widget_most_comm");'));文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

现在打开你的后台的小工具选项就会有一个“Devework.com热门文章”小工具,直接拖动使用即可。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/cms/38253.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/cms/38253.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定