探索建站和运维乐趣

无插件实现WordPress随机文章列表调用方法

我们很多网友在搭建个人博客或者其他网站的时候,有些网站的侧边是空白较多,于是想着放点什么内容充实一下。于是,有的会想到放一张图片,有的会考虑调用文章的随机文章。其实从网站运营角度看,如果调用随机文章的时候,还会给网站传递权重。如果我们有需要在WordPress网站添加随机文章的话,可以通过下面我们整理的办法调用。

1、直接简单的方法

<?php
$args = array( 'numberposts' => 8, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>

在需要调用随机文章的位置贴上代码,需要在上面代码中设置调出的数量。默认是8,我们可以修改数字。

2、Functions.php方法

/**
 * 随机文章调用 laobuluo.com
 */
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;
}

代码贴到当前主题 Functions.php 文件中。

<?php random_posts(); ?>

在合适的位置和样式中加入代码调用。

3、同分类随机文章

<?php
$cat = get_the_category();
foreach($cat as $key=>$category){
$catid = $category->term_id;
}
$args = array('orderby' => 'rand','showposts' => 6,'cat' => $catid );
$query_posts = new WP_Query();
$query_posts->query($args);
while ($query_posts->have_posts()) : $query_posts->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
<?php wp_reset_query(); ?>

如果我们需要调用同分类中的随机文章可以用这个。需要手动设置调用条数,上面代码默认的是6,我们可以自己修改。

赞(0)
转载保留:老部落 » 无插件实现WordPress随机文章列表调用方法


关注公众号『老蒋朋友圈』

获取更多建站运营运维新知!
互联网创业、前沿技术......