为wordpress主题添加随机文章小工具

创意威客 2019-2-2 2269

目前wordpress主题站启用了2014杂志主题,这款非常给力的主题,视觉有点冲击的感觉,可能是老主题用久了?由于这款自带主题2014没有附带随机文章的小工具,于是就百度查找了下,你懂得,半个伸手党了。

使用随机文章的好处:

避免好的文章被淹没了,搜索引擎每次来访问的是不同的链接,增加内链。可以自由拖放,与其他小工具搭配使用,避免写在侧边栏过于死板。

为WP主题添加随机文章小工具方法:

首先找到主题的functions.php在?>之前添加如下代码并上传覆盖到主题目录:

//随机文章
class RandomPostWidget extends WP_Widget
{
function RandomPostWidget()
{
parent::WP_Widget('bd_random_post_widget', '随机文章', array('description' => '我的随机文章小工具') );
}
function widget($args, $instance)
{
extract( $args );
$title = apply_filters('widget_title',empty($instance['title']) ? '随机文章' :
$instance['title'], $instance, $this->id_base);
if ( empty( $instance['number'] ) || ! $number = absint( $instance['number'] ) )
{
$number = 10;
}
$r = new WP_Query(array('posts_per_page' => $number, 'no_found_rows' => true,
'post_status' => 'publish', 'ignore_sticky_posts' => true, 'orderby' =>'rand'));
if ($r->have_posts())
{
echo "n";
echo $before_widget;
if ( $title ) echo $before_title . $title . $after_title;
?>
<ul>
<?php while ($r->have_posts()) : $r->the_post(); ?>
<li style="border-top: 1px solid rgba(255, 255, 255, 0.2); padding: 8px 0 9px;border-color: rgba(0, 0, 0, 0.1);"><a href="<?php the_permalink() ?>" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?></a></li>
<?php endwhile; ?>
</ul><?php
echo $after_widget;
wp_reset_postdata();
}
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['number'] = (int) $new_instance['number'];
return $instance;
}
function form($instance)
{
$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
$number = isset($instance['number']) ? absint($instance['number']) : 10;?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input 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('文章显示数量:'); ?></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("RandomPostWidget");'));

什么?看不懂?没关系,不需要看懂,实在怕搞错的,不想动手的童鞋可以试一试插件的方法,比如:中文工具箱、Random Pages Widget等等。


最新回复 (0)
全部楼主
返回