以前曾经分享了一篇 给wordpress后台小工具增加一个随机文章,但没有附加缩略图的功能,为了让你的随机文章看起来更吸睛,这里加上特色图像的缩略图,效果如本站左边栏的随机文章,步骤和代码如下:
后台-外观-小工具-效果如下图:
开始之前你需要了解 Widget 函数如何创建自定义侧边栏小工具,本站有篇文章详细介绍了用法和实例,wordpress主题开发创建你喜欢的小工具
流程:
一、主题根目录下创建rand-posts.PHP
二、在functions.PHP文件中导入rand-posts.PHP,这样做的目的是不让functions.PHP太臃肿,独立出来好管理。
/**
* 带缩略图的随机文章
*/
require get_template_directory() . '/inc/rand-posts.PHP';
三、根据你的主题样式,在style.CSS定义你的前端显示样式,为了你方便修改样式表,我这里给 li 加了类class='rp-thumb'。
rand-posts.PHP源码
点击 rand-posts.PHP源码
/**
* 带缩略图的 随机文章小工具
*
* web:www.511yj.com
*/
class yj_Random_posts extends WP_Widget {
public function __construct() {
parent::__construct(
'yj_rp_random',// Base ID
__('随机文章','yj'),// name
array( 'description' => __( 'yj-带缩略图的随机文章小工具.','yj' ),) // Args
);
}
public function Widget( $args,$instance ) {
if (isset($instance['Title'])) :
$Title = apply_filters( 'Widget_Title',$instance['Title'] );
$no_of_posts = apply_filters( 'no_of_posts',$instance['no_of_posts'] );
else :
$Title = __('Latest posts','yj');
$no_of_posts = 5;
endif;
echo $args['before_Widget'];
if ( ! empty( $Title ) )
echo $args['before_Title'] . $Title . $args['after_Title'];
// WP_query arguments
$qa = array (
'post_type' => 'post',
'posts_per_page' => $no_of_posts,
'offset' => 0,
'ignore_sticky_posts' => 1,
'orderby' =>'rand'
);
// The query
$recent_articles = new WP_query( $qa );
if($recent_articles->have_posts()) : ?>
while($recent_articles->have_posts()) :
$recent_articles->the_post();
?>
else :
?>
endif; ?>
enDWhile;
else:
?>
Oops,there are no posts.
endif;
?>
echo $args['after_Widget'];
}
public function form( $instance ) {
if ( isset( $instance[ 'Title' ] ) ) {
$Title = $instance[ 'Title' ];
}
else {
$Title = __( '随机文章','yj' );
}
if ( isset( $instance[ 'no_of_posts' ] ) ) {
$no_of_posts = $instance[ 'no_of_posts' ];
}
else {
$no_of_posts = __( '5','yj' );
}
?>
评论列表(0条)