My Computer · 2023/08/10 0

wordpress 6.3 纯代码非插件方式调用随机文章

高手自己写,水平不济的百度搜,可惜都是老掉牙的代码根本不能用

找了ChatGPT大哥帮忙,大哥毫不含糊给出代码,6.3版本一切正常

<?php
// 获取随机5篇已发布文章的标题和链接
$random_args = array(
    'post_type'      => 'post',   // 文章类型
    'orderby'        => 'rand',   // 按随机顺序排序
    'posts_per_page' => 5,        // 显示5篇文章
    'post_status'    => 'publish' // 仅显示已发布的文章
);

$random_query = new WP_Query( $random_args );

// 输出文章标题和链接
if ( $random_query->have_posts() ) {
    while ( $random_query->have_posts() ) {
        $random_query->the_post();
        ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <?php
    }
    wp_reset_postdata(); // 重置文章数据
}
?>

上述代码将获取随机的5篇已发布文章,并在页面上显示它们的标题,每个标题都链接到相应的文章页面。您可以根据需要进行自定义,比如更改文章类型、调整显示数量等。

再次提醒,进行代码修改前最好备份您的主题文件。如果您不熟悉代码操作,建议您先了解基本的PHP和WordPress开发知识,或者寻求专业开发人员的帮助。

相关文章