A5下载 - 努力做内容最丰富最安全的下载站!

A5站长下载站

当前位置:A5下载 > 源码技巧 > wordpress > wordpress不用插件用ajax刷新边栏随机文章的方法

wordpress不用插件用ajax刷新边栏随机文章的方法

时间:2015-10-16 13:38作者:fang人气:60

现在给大家分享下如何利用ajax刷新wordpress边栏的随机文章吧。

DEMO

点击本博客边栏的 “刷新一下”就可以看到。

如何实现?

首先确认你的主题中调用了js库,在主题文件header.php可以找到以下代码 。没有的话,请复制粘贴放在标签前。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

1、确定随即文章代码中id的范围。本博客的随机文章html代码大致如下所示。你也可以在你的网站模板中找到类似的代码。每个主题的调用函数大同小异,中间一大串的代码可以忽略。

<h2 class="sub">推荐阅读</h2>

< div id="postlist1">

<ul class="spy">

<?php $my_query = new WP_Query('orderby=rand&showposts=5'); ?>

<?php while ($my_query->have_posts()) : $my_query->the_post();?>

<li><?php $screen = get_post_meta($post->ID, 'screen', $single = true); ?>

<h2 style="overflow:hidden;"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>

</li>

?php endwhile; ?>

</ul>

< /div>

< a href="#" id="another">刷新一下</a>

其中,你还需要添加个“刷新一下”到你的随即文章代码里 。也就是下面的代码。

<a href="#" id="another">刷新一下</a>

同时注意在 ul 标签前面的ID “postlist1” 和最后一个包裹“刷新”的ID “another”,下面的步骤会用到。

2、创建一个页面模板,名为Random Post。PS:下面的代码不要照搬。其中的随即文章调用函数从自己当前使用的主题中的sidebar.php直接复制进来。

<?php

/*

Template Name: Random Post

*/

?>

< ?php $my_query = new WP_Query('orderby=rand&showposts=5'); ?>

< ?php while ($my_query->have_posts()) : $my_query->the_post();?>

< li><?php $screen = get_post_meta($post->ID, 'screen', $single = true); ?>

< h2 style="overflow:hidden;"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>

< /li>

< ?php endwhile; ?>

3、创建一个使用上面模板的页面,并发布。

大家可以点击这里查看本站的这个页面 /random

4、jQuery

复制粘贴以下代码到你主题 header.php文件中,放在标签前。

其中的#polist1 和#another 在步骤一找到,结合你自身的主题更改。

<script type="text/javascript" charset="utf-8">

$().ready(function(){

$("#postlist1").load("/random/?offset="+offset);

$("#another").click(function(){

offset = offset+5;

$("#postlist1")

.slideUp()

.load("/random/?offset="+offset, function() {

$(this).slideDown();

});

});

< /script>

5 直至全部结束,大功告成!

标签wordpress,不用,插件,ajax,刷新,边栏,随机

相关下载

查看所有评论+

网友评论

网友
您的评论需要经过审核才能显示

热门阅览

最新排行

公众号