找到主题目录下的functions.php,里面新增如下代码, 废话不多说直接上代码
<?php
// 注册小工具
class WP_Widget_Tags_Relation_Posts extends WP_Widget {
function __construct() {
$widget_ops = array(
'classname' => 'widget_tags_relation_posts',
'description' => __( '相关推荐 【made by zhouch】' )
);
parent::__construct('relation-posts', __('相关推荐'), $widget_ops);
$this->alt_option_name = 'widget_tags_realtion_posts';
}
function widget( $args, $instance ) {
global $relation_posts, $post;
extract($args, EXTR_SKIP);
// 必须为文章页
if ( is_single() ) {
$post_tags = wp_get_post_tags($post->ID);
$output = '';
// 设置 widget 标题
$title = apply_filters('widget_title', empty($instance['title']) ? __('相关推荐') : $instance['title']);
// 设置要获取的文章数目
if ( ! $number = absint( $instance['number'] ) )
$number = 5;
// WP 数据库查询,
if ($post_tags) {
foreach ($post_tags as $tag) {
// 获取标签列表
$tag_list[] .= $tag->term_id;
}
$args = array(
'tag__in' => $tag_list,
'category__not_in' => array(NULL), // 不包括的分类ID
'post__not_in' => array($post->ID),
'showposts' => $number, // 显示相关文章数量
'caller_get_posts' => 1
);
$relation_posts = query_posts($args);
if ( $relation_posts ) {
// 先输出一般的 widget 前缀
$output .= $before_widget;
// 输出标题
if ( $title )
$output .= $before_title . $title . $after_title;
// relation posts 列表开始
$output .= '<ul id="relation_posts">';
foreach ( (array) $relation_posts as $post) {
$output .= '<li><a href="' . get_permalink() . '">' . $post->post_title . '</a></li>';
}
$output .= '</ul>';
// 输出一般的 widget 后缀
$output .= $after_widget;
}
}
// 输出到页面
echo $output;
} else {
echo '';
}
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['number'] = absint( $new_instance['number'] );
$alloptions = wp_cache_get( 'alloptions', 'options' );
if ( isset($alloptions['widget_tags_realtion_posts']) )
delete_option('widget_tags_realtion_posts');
return $instance;
}
// 在 WP 后台的 widget 内部显示两个参数, 1. 标题;2. 显示文章数目
function form( $instance ) {
$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
$number = isset($instance['number']) ? absint($instance['number']) : 5;
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input class="cnzhx" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts to show:'); ?></label>
<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
<?php
}
}
add_action( 'widgets_init', create_function( '', 'return register_widget("WP_Widget_Tags_Relation_Posts");' ) );
现在可以在wordpress管理后台里看到有个小工具了。
拖拽到相应位置即可