adm" />

wordpress添加一个随机文章按钮:换一换

类似换一换按钮,按钮通过div置放,给dom绑定事件就可以了。

1、把下面的代码放到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; }); });
2、添加按钮
<?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");}

代码可以直接放到安装位轩置,也可以放在footer.php文件中。

#现在前往

精选留言

wordpress,添加,一个,随机
sample
2021-01-16
写留言
签到
投稿
QQ咨询
返回顶部