wordpress教程 wordpress调用指定ID文章的代码

最近又在折腾wordpress主题模板 遇到“调用指定ID文章”的需求,折腾一番成功后分享下:
相关代码:

<?php 
$postsl = get_posts("numberposts=4&post_type=any&include=1,2,3"); 
if($postsl) : foreach( $postsl as $post ) : setup_postdata( $post ); 
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
<?php endforeach; endif; ?>

将这段代码放到你所需要的位置即可。CSS样式根据自己的主题自行调整。

上面代码中的“1,2,3”表示要调用的文章id。

numberposts=4 表示调用4篇文章

post_type=any 表示调用的类型 post(日志),page(页面),attachment(附件),any (所有)

相关参数详解:

<?php
$args = array(
  //需要提取的文章数
  'numberposts'   => 10,
  
  //以第几篇文章为起始位置
  'offset'     => 0,
  
  //分类的ID,多个用逗号将分类编号隔开,或传递编号数组,可指定多个分类编号。
  //大部分 CMS 使用该函数的重点。
  'category'    => ,
  
  //排序规则(注1)
  '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' );
?>

注:

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

最后分享下如果要把这东西做到后台主题设置里面怎么添加:

先把自定义字段设置好,然后这么写:

<?php 
$hostid = $options['theme_hotid']; 
$postsl = get_posts("numberposts=4&post_type=any&include=".$hostid); 
if($postsl) : foreach( $postsl as $post ) : setup_postdata( $post ); 
?>

上面这段代码中的“$options[‘theme_hotid’]”就是主题自定义字段名称。

get_posts 该函数属于 WordPress 的内置函数,用于在 WordPress 中提取多篇指定或随机文章。

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论