wordpress使用get_posts()函数获取指定ID多篇文章

  • 2020-12-17 19:17:07
  • 1,906 次阅读
  • 稿源:博客园

wordpress内置函数get_posts()用于调用指定的一篇或多篇文章,函数提供多个参数,可以设置调用文章的指定分类、自定义字段、文章类型、文章状态、显示顺序等条件,文章以数组的形式返回,通过循环语句输出即可。

wordpress使用get_posts()函数获取指定ID多篇文章

代码结构:

  1. <?php get_posts($args);?>

返回数组型的变量,$args是该函数必要的变量

变量$args参数:

  1. <?php
  2. $args = array(
  3. //显示的文章数量
  4. 'numberposts' => 10,
  5. //以第几篇文章为起始位置
  6. 'offset' => 0,
  7. //调用分类的ID,多个用逗号将分类编号隔开,或传递编号数组,可指定多个分类编号。
  8. 'category' => ,
  9. //文章排序规则
  10. 'orderby' => 'post_date',
  11. //升序、降序 'ASC' —— 升序 (低到高) 'DESC' —— 降序 (高到底)
  12. 'order' => 'DESC',
  13. //要显示文章的ID
  14. 'include' => ,
  15. //要排除文章的ID
  16. 'exclude' => ,
  17. //自定义字段名称
  18. 'meta_key' => ,
  19. //自定义字段的值,配合上一个参数,来选择显示符合自定义字段数值的文章。
  20. 'meta_value' => ,
  21. //post(日志)——默认,page(页面),attachment(附件),any —— (所有)
  22. 'post_type' => 'post',
  23. //文章的 mime 类型
  24. 'post_mime_type' => ,
  25. //要显示文章的父级 ID
  26. 'post_parent' => ,
  27. //文章状态
  28. 'post_status' => 'publish' );
  29. ?>

orderby排列顺序可选的值:

  1. author —— 按作者数值编号排序
  2. category —— 按类别数值编号排序
  3. content —— 按内容排序
  4. date —— 按创建日期排序
  5. ID —— 按文章编号排序
  6. menu_order —— 按菜单顺序排序。仅页面可用。
  7. mime_type —— MIME类型排序。仅附件可用。
  8. modified —— 按最后修改时间排序。
  9. name —— 按存根排序。
  10. parent —— 按父级ID排序
  11. password —— 按密码排序
  12. rand —— 任意排序结果
  13. status —— 按状态排序
  14. title —— 按标题排序
  15. type —— 按类型排序

示例:调用指定ID为1,3,4,6的四篇文章

  1. <?php $posts = get_posts("numberposts=4&post_type=any&include=1,3,4,6"); if($posts) : foreach( $posts as $post ) : setup_postdata( $post ); ?>
  2. <li>
  3. <h2><a title="<?php the_title();?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title();?></a></h2>
  4. <div class="thumbnail">
  5. <a title="<?php the_title();?>" href="<?php the_permalink(); ?>"><?php if((function_exists('has_post_thumbnail')) && (has_post_thumbnail())){$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()) );?><img src="<?php echo $thumbnail_src[0];?>"/><?php }else {?><img alt="<?php the_title();?>" src="<?php echo catch_that_image(); ?>"/><?php } ?></a>
  6. </div>
  7. <div class="views-con">
  8. <p><?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 100,"……"); ?></p>
  9. </div>
  10. <div class="views-read">
  11. <a title="<?php the_title();?>" href="<?php the_permalink(); ?>">阅读全文</a>
  12. </div>
  13. </li>
  14. <?php endforeach; endif; ?>

喜欢 4

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头