wordpress不用插件调用指定条数的随机文章

引用请注明出处: https://seonoco.com/blog/1297

NOCO发布于 分类 Wordpress

598天前 有1个用户阅读过

本文来自我的百度空间博客详情

2007年开始使用的是 hi.baidu.com/udjy
后来百度空间强制升级为轻博客 hi.baidu.com/imnoco
2015年百度关闭了百度空间

真理:插件多了容易影响wordpress网站性能(复制的时候注意引号是否是英文, 避免全角的中文引号)

wordpress随机文章(随机日志)四种实现方法。wordpress添加随机文章可以用插件,也可以用代码实现,不过个人还是比较喜欢用代码来实现,毕竟代码也挺简单的时候用插件就真是有点浪费网站资源了。

 

wordpress随机文章实现方法一

 

在function.php中加入如下方法

 

/**
* 随机文章
*/
function random_posts($posts_num=5,$before='<li>',$after='</li>'){
    global $wpdb;
    $sql ="SELECT ID, post_title,guid
            FROM $wpdb->posts
            WHERE post_status = 'publish'";
    $sql .="AND post_title != ''";
    $sql .="AND post_password =''";
    $sql .="AND post_type = 'post'";
    $sql .="ORDER BY RAND() LIMIT 0 , $posts_num";
    $randposts = $wpdb->get_results($sql);
    $output = '';
    foreach ($randposts as $randpost) {
        $post_title = stripslashes($randpost->post_title);
        $permalink = get_permalink($randpost->ID);
        $output .= $before.'<a href="'
            . $permalink . '"  rel="bookmark" title="';
        $output .= $post_title . '">' . $post_title . '</a>';
        $output .= $after;
    }
    echo $output;
}

 

在需要显示的地方调用如下代码

 

<div class="right">
    <h3>随便找点看看!</h3>
    <ul>
        <?php random_posts(); ?>
    </ul>
</div><!-- 随机文章 -->

 

不复杂吧,以上代码不依赖也不影响其他代码。

 

wordpress随机文章实现方法二 (个人比较喜欢这种)

 

在需要显示的地方直接调用如下代码

 

<ul>
<?php $rand_posts = get_posts('numberposts=5&orderby=rand');
foreach( $rand_posts as $post ) : ?>
   <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
   </li>
<?php endforeach; ?>
</ul>

 

wordpress随机文章实现方法三:用query_posts生成随机文章列表

 

在需要显示的地方直接调用如下代码

 

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 2));
if (have_posts()) :
while (have_posts()) : the_post();?>
<a href="<?php the_permalink() ?>"
    rel="bookmark"
    title=<?php the_title(); ?>"><?php the_title(); ?></a> 
    <?php comments_number(", '(1)', '(%)'); ?>
<?php endwhile;endif; ?>

 

wordpress随机文章实现方法四:支持在随机文章中显示标题和文章摘要

 

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); //这行去掉就不显示标题
the_excerpt(); //去掉这个就不显示摘要了
endwhile;
endif; ?>

 

在wordpress随机文章实现的4种方法中除了第一种方法,其他三种方法中都使用到了,get_posts、the_post等方法,这些方法破坏页面中记录的当前文章的信息,如果使用在页面的最后部分,影响不大,如果在调用的代码后面还有评论等内容,则会导致评论内容调用的是随机到的最后一篇文章的评论。

 

-- The End --

本文标题: wordpress不用插件调用指定条数的随机文章

本文地址: https://seonoco.com/blog/1297

本文是否有所帮助?
点赞 0
感谢支持
0
多谢反馈
评论 0
打赏

支持微信/支付宝

评论

网友