国内外主机
测评及优惠码

WordPress随机文章的实现方式与用法

ralix曾发布过关于WordPress随机文章的相关插件点评文章(“wordpress插件之随机文章类插件点评”),百度一下也能搜出很多其他纯代码的方式,大致代码如下:

<?php $query = array( 	'post_type'	=> 'post', 	'orderby'	=> 'rand' ); $posts = new WP_Query( $query ); if ( $posts->have_posts() ) { 	while( $posts->have_posts() ) : 			$posts->the_post(); 			the_content(); 	endwhile; } wp_reset_query(); ?>

回头来看看这一段代码,其实很简单,在理解了的前提下,提出需要实现“随机推荐”,该怎么实现呢?

WordPress实现随机推荐

在帮一个朋友修改主题的时候,他要求在侧边栏加上一个随机推荐的功能,为了减少工作量,将置顶文章默认为值得推荐的文章(或许有其他简便的方法),实现代码如下:

<?php //获取置顶文章的ID串 $rand_id = get_option( 'sticky_posts' ); $query = array( 	'post__in'	=> $rand_id, 	'post_type'	=> 'post', 	'orderyby'	=> 'rand', 	'numberposts'	=> 2 ); $posts = new WP_Query( $query ); if ( $posts->have_posts() ) { 	while( $posts->have_posts() ) : 			$posts->the_post(); 			the_content(); 	endwhile; } wp_reset_query(); ?>

至于添加到widgets这里就不详说了。

进阶应用:随便看看的功能实现

现在来看看“随便看看”是怎么实现的?
其实实现这样的功能也不难,首先在后台主题“菜单”里,添加自定义链接,链接地址写成“http://yourdomain.com/random”或者“http://yourdomain.com/index.php?random=1”之类的都行。
然后在当前主题文件下的functions.php里添加如下代码:

<?php add_action('init','random_add_rewrite'); add_action('template_redirect','random_template'); function random_add_rewrite() {        global $wp;        $wp-&gt;add_query_var('random');        add_rewrite_rule('random/?$', 'index.php?random=1', 'top'); } function random_template() {        if (get_query_var('random') == 1) {                $posts = get_posts('post_type=post&amp;orderby=rand&amp;numberposts=1');                foreach($posts as $post) {                        $random_link = get_permalink($post);                }                wp_redirect($random_link,307); //307临时跳转                exit;        } } ?>

至此,效果已经实现(注:貌似3.3以前的老版本,需要进固定链接,执行一下“保存更改”才有效果)!当然网上也有通过新建页面,然后用javascript跳转的方法,大家也可以借鉴借鉴。

赞一个
赞(0)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《WordPress随机文章的实现方式与用法》
文章链接:https://www.ibytx.com/1354.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

登录

找回密码

注册