您的当前位置:首页 > 知识博客 > wordpress建站

WordPress不用插件实现随机文章

时间:2024-03-16

WordPress原生没有输出随机文章列表的函数,虽然有一些插件可以实现,但过多的插件会拖慢WordPress的访问速度,因此,我们可以自己写一个函数来实现。

在主题文件functions.php中插入以下代码:

function bzg_random_posts($limit=10, $word=32, $isdate=false) {
	$rand_posts = get_posts('posts_per_page=' . $limit .'&orderby=rand');
	foreach( $rand_posts as $post ) {
		if($isdate) $article_time = '<time datetime="' . get_the_time( 'c', $post->ID ) . '">' . get_the_time('Y-m-d', $post->ID) . '</time>';
		echo '<li><a href="' . get_permalink($post->ID) . '" rel="bookmark">' . mb_strimwidth($post->post_title, 0, $word) . '</a>' . $article_time . '</li>';
	}
	wp_reset_postdata();
}

在需要输出随机文章列表的地方插入以下代码:

<?php bzg_random_posts(10, 32, false); ?>

函数参数说明:

  • $limit:输出文章的数量;

  • $word:文章标题的长度;

  • $isdate:是否输出文章日期,true表示输出文章日期,false表示不输出文章日期。


欢迎咨询/Welcome to inquire
tel/vx:18842938855
qq:1685522781
email:1685522781@qq.com

Copyright © 2019-2024 mysql.hk


Whatsapp
Powered by RRZCMS