获取Wordpress帖子的主映像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取Wordpress帖子的主映像相关的知识,希望对你有一定的参考价值。

If post has featured image, use it.. If not, pick out the first in the post.. Still not working? Stick with the default one..
  1. <?php
  2.  
  3. //Put this in functions.php
  4.  
  5. function get_primary_image($id, $size){
  6. $featured = wp_get_attachment_image_src( get_post_thumbnail_id($id), $size, false);
  7. if($featured){
  8. $childURL = $featured['0'];
  9. }else{
  10. $children = get_children(array('post_parent' => $id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1));
  11. reset($children);
  12. $childID = key($children);
  13. //$childURL = wp_get_attachment_url($childID);
  14. $childArray = wp_get_attachment_image_src($childID, $size, false);
  15. $childURL = $childArray['0'];
  16. if(empty($childURL)){
  17. $childURL = get_bloginfo('template_url')."/images/default.png";
  18. }
  19. }
  20. return($childURL);
  21. }
  22.  
  23.  
  24. //Run this in the loop (or any place you'd like - as long as you have an ID to feed it..)
  25. //First argument is the ID..
  26. //Second argument is the size.. It'll handle 'large', 'medium', 'thumbnail' or even
  27.  
  28. 'array(100, 100)'..
  29. get_primary_image(get_the_ID(), 'large');
  30.  
  31. ?>

以上是关于获取Wordpress帖子的主映像的主要内容,如果未能解决你的问题,请参考以下文章

如何将页面中的特色图像缩略图放在 wordpress 的主索引上

获取自定义帖子而不是默认的 Wordpress 帖子

从帖子标题获取 WordPress 帖子 ID

Wordpress:逐月获取帖子,布局问题

Wordpress 如何仅获取自定义帖子类型的父帖子

Wordpress - 如何通过 AJAX 获取更多帖子?