無需插件 利用ajax刷新wordpress邊欄隨機(jī)文章

字號(hào):


    有個(gè)朋友發(fā)信問我,我的邊欄那個(gè)刷新一下的效果是如何實(shí)現(xiàn)的。能不能分享?cms教程欄目
    其實(shí),我這幾天就打算分享出來,就是時(shí)間不允許,現(xiàn)在就給大家分享下如何利用ajax刷新wordpress邊欄的隨機(jī)文章吧。
    demo
    點(diǎn)擊本博客邊欄的 “刷新一下”就可以看到。
    如何實(shí)現(xiàn)?
    首先確認(rèn)你的主題中調(diào)用了js庫,在主題文件header.php可以找到以下代碼 。沒有的話,請(qǐng)復(fù)制粘貼放在標(biāo)簽前。
    <script type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js></script>
    1 確定隨即文章代碼中id的范圍。本博客的隨機(jī)文章html代碼大致如下所示。你也可以在你的主題模板中找到類似的代碼。每個(gè)主題的調(diào)用函數(shù)大同小異,中間一大串的代碼可以忽略。
    <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>
    其中,你還需要添加個(gè)“刷新一下”到你的隨即文章代碼里 。也就是下面的代碼。
    <a href=# id=another>刷新一下</a> 
    同時(shí)注意在 ul 標(biāo)簽前面的id “postlist1” 和最后一個(gè)包裹“刷新”的id “another”,下面的步驟會(huì)用到。
    2 創(chuàng)建一個(gè)頁面模板,名為random post。ps:下面的代碼不要照搬。其中的隨即文章調(diào)用函數(shù)從自己當(dāng)前使用的主題中的sidebar.php直接復(fù)制進(jìn)來。
    <?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 創(chuàng)建一個(gè)使用上面模板的頁面,并發(fā)布。
    大家可以點(diǎn)擊這里查看本站的這個(gè)頁面 /random
    4 jquery
    復(fù)制粘貼以下代碼到你主題 header.php文件中,放在標(biāo)簽前。
    其中的#polist1 和#another 在步驟一找到,結(jié)合你自身的主題更改。
    <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 直至全部結(jié)束,大功告成!