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

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

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

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

代码结构:

<?php get_posts($args);?>

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

变量$args参数:

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

orderby排列顺序可选的值:

‘author’ —— 按作者数值编号排序
‘category’ —— 按类别数值编号排序
‘content’ —— 按内容排序
‘date’ —— 按创建日期排序
‘ID’ —— 按文章编号排序
‘menu_order’ —— 按菜单顺序排序。仅页面可用。
‘mime_type’ —— 按MIME类型排序。仅附件可用。
‘modified’ —— 按最后修改时间排序。
‘name’ —— 按存根排序。
‘parent’ —— 按父级ID排序
‘password’ —— 按密码排序
‘rand’ —— 任意排序结果
‘status’ —— 按状态排序
‘title’ —— 按标题排序
‘type’ —— 按类型排序

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

<?php $posts = get_posts("numberposts=4&post_type=any&include=1,3,4,6"); if($posts) : foreach( $posts as $post ) : setup_postdata( $post ); ?>
<li>
	<h2><a title="<?php the_title();?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title();?></a></h2>
	<div class="thumbnail">
		<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>
	</div>
	<div class="views-con">
		<p><?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 100,"……"); ?></p>
	</div>
	<div class="views-read">
		<a title="<?php the_title();?>" href="<?php the_permalink(); ?>">阅读全文</a>
	</div>
</li>
<?php endforeach; endif; ?>
喜欢 4

文章评论 (0)

表情

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