给wordpress增加一个随机文章按钮
这个功能想了很久了,还是大发老师给力。
不少网站都有随机文章的功能,包括之前我的写过一个,但是那个实现方法比较蛋疼,这次的实现方式更先进一些,样式还可以。按钮你可以随便放在哪,只要注意给dom绑定事件就可以了。
把下面的代码放到functions.php
中
wp_enqueue_script( 'base', true); wp_localize_script('base', 'Bigfa', array( "ajaxurl" => admin_url('admin-ajax.php') )); add_action( 'wp_ajax_random_post', 'bigfa_random_post' ); add_action( 'wp_ajax_nopriv_random_post', 'bigfa_random_post' ); function bigfa_random_post() { $posts = get_posts('post_type=post&orderby=rand&numberposts=1'); foreach($posts as $post) { $link = get_permalink($post); } echo $link; exit; }
JS代码,需要1.7以上版本的JQ库
jQuery('.random_post').on('click', function(e) { e.preventDefault(); jQuery.post(Bigfa.ajaxurl, { action : 'random_post', }, function(data) { window.location.href = data; }); });
在你想使用的地方放上按钮,我是直接仍在了footer.php中
<?php if(!wp_is_mobile()) echo '<a href="javascript:void(0)"> </a>';?>
css参考样式
.random_post {background-color: #E8E8E8;background-image: url("img/random_icon_normal.png");background-position: center center;background-repeat: no-repeat;height: 16px;margin-top: -60px;padding: 20px 10px;position: fixed;right: 0;top: 50%;width: 19px;} .random_post:hover{background-color:#F36639;background-image: url("img/random_icon_hover.png");}