重庆SEO培训(WordPress小工具添加随机文章列表)

重庆SEO培训课程。WordPress小工具可以更好地让我们在不同的页面展现不同的内容,随机文章列表就是一个非常不错的选择,可以让蜘蛛更容易爬行并抓取整站所有内容。今天,小小课堂网(www.xxkt.org)分享的内容为《重庆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="<?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培训

以上就是小小课堂网(www.xxkt.org)分享的内容为《重庆SEO培训(WordPress小工具添加随机文章列表)》。感谢您的阅读。

所有文章均为小小课堂网原创。发布者:SEO免费培训教程,转转请注明出处:https://www.xxkt.org/15410

(0)
上一篇 2022年2月26日 下午5:06
下一篇 2022年2月26日 下午5:44

相关推荐

发表评论

您的电子邮箱地址不会被公开。

error: Content is protected !!