无需插件 利用ajax刷新wordpress边栏随机文章

wordpress 12年前 (2012) 工具猫
1,889 0

有个朋友发信问我,我的边栏那个刷新一下的效果是如何实现的。能不能分享?

其实,我这几天就打算分享出来,就是时间不允许,现在就给大家分享下如何利用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>推荐阅读</h2>
<div id="postlist1">
<ul>
<?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 直至全部结束,大功告成!

原文地址:http://yeahlee.com

版权声明:工具猫 发表于 2012-12-07 14:41:57。
转载请注明:无需插件 利用ajax刷新wordpress边栏随机文章 | 工具猫