WordPress在网站建设开发中进行随机文章调用输出的3个方法

用wordpress系统进行网站开发时,经常会用到随机调用数据信息的需求。这样对于我们页面或是详细页中,这样每次访问时就会展示不同的数据,每次都会更新不同的数据,这样可以给网站用户访问一种每次不同的访问变化与数据展示。

1、最常见的调用随机代码,这样也比较容易懂,调用数据也比较简单。

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

2、也可以采用 query_posts 生成随机文章列表,但是这种一般只应用于 post 常规组件调用。

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

3、这个是应用于本分类随机文章数据进行调用

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

主题测试文章,只做测试使用。发布者:zhaolou,转转请注明出处:https://www.zhaolou.cc/archives/4229

(0)
zhaolou's avatarzhaolou
上一篇 2025年3月22日 上午10:14
下一篇 2025年3月22日 上午10:16

相关推荐

  • wordpress常用标签大全

    WordPress Header头部 PHP代码 <?php bloginfo(‘name’); ?> 网站标题 <?php wp_title(); ?> 日志或页面标题 <?php bloginfo(‘stylesheet_url’); ?> WordPress主题样式表文件style.cs…

    外贸 2025年4月19日
    1.8K00
  • 如何用 Semrush + Google Trends + Ahrefs 高效挖掘关键词?

    作为Google SEO中最核心的一步,关键词挖掘不仅关系到流量多少,还决定了你内容能否打入目标用户搜索视野。本文以“xxx”为例,带你实操一遍关键词挖掘与筛选的完整流程。 ✅ Step 1:用 Semrush 查询关键词基础数据(Keyword Overview) 打开 Semrush,在左侧点击【Keyword Overview】,输入你想查询的关键词,…

    google seo 2025年5月14日
    4.1K00
  • WordPress 时间日期函数

    我们用wordpress系统进行网站建设开发网站时,关于wordpress的时间相关函数应用,以及wp的时间显示函数。 1、输出 2024-12-25 <?phpthe_time(‘Y-m-d’);?> 2、输出时间,如:10:35:28 <?phpthe_time(‘G:i:s’);?> 3、输出 2024年12月25日 <?…

    外贸 2025年3月22日
    1.7K00
  • wordpress获取分类下文章列表四种方法

    1、使用query_posts()函数以下代码实际上使用query_posts()函数调取分类目录下的文章,showposts是调取的数量。 <?php $cats = get_categories(); foreach ( $cats as $cat ) { query_posts( ‘showposts=10&cat=’ . $cat-&g…

    外贸 2025年3月22日
    1.7K00
  • 美国苹果账号(Apple ID)注册方法

    准备工作: 1、提前注册一个国内的Apple ID(这个无需多说) 2、准备电脑一台,或者手机一部 开始注册美国Apple ID: 1、先进入苹果Apple ID官网https://appleid.apple.com/#!&page=signin,然后选择“登录”! 2、输入你提前准备好了的国内的Apple ID,输入账号和密码,并登录!(不建议使用…

    2025年6月1日
    2.6K00

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

在线咨询: QQ交谈

邮件:156738051@qq.com

工作时间:周一至周五,9:00-18:00,节假日休息

关注微信