重庆SEO培训课程。WordPress小工具可以更好地让我们在不同的页面展现不同的内容,随机文章列表就是一个非常不错的选择,可以让蜘蛛更容易爬行并抓取整站所有内容。今天,烨晟网络(www.yeshengweb.com)分享的内容为《重庆SEO培训(WordPress小工具添加随机文章列表)》。希望对大家有所帮助。

本代码适用于PHP 5.2及以上版本,低于5.2的不能正常运行。

直接在网站模板文件 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 class="line">
<?php  while ($r->have_posts()) : $r->the_post(); ?>
<li><a href="https://www.xxkt.org/15410/<?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('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("RandomPostWidget");'));
?>

添加完成之后,就可以看到在“外观”>“小工具”中找到“随机列表”了,标题默认不写就是“随机文章”,如果不喜欢这个名字,就可以改为其他,比如热门文章等等。

重庆SEO培训

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。