基于类别的随机特征图像

时间:2013-09-11 作者:RonnieT

我希望扩展下面的代码,根据特定类别选择一个随机特征图像。下面的方法可行,但使用了一个总体图像列表来从基于特定类别的图像列表中提取图像。在下面,任意选择以“UF-”开头的任何图像作为特征图像。

有人能帮我指出正确的方向吗?理想情况下,希望每个类别都有几个随机使用的图像。

function autoset_featured() {
     global $post;
     $already_has_thumb = has_post_thumbnail($post->ID);
     if (!$already_has_thumb)  {
         $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
         if ($attached_image) {
              foreach ($attached_image as $attachment_id => $attachment) {
                   set_post_thumbnail($post->ID, $attachment_id);
              }
         } else {
              set_post_thumbnail($post->ID, get_image());
         }
     }
}

function get_image(){
     $list = array();
     $data = array();

     $media_query = new WP_Query(
                    array(  \'post_status\' => \'inherit\',
                            \'post_parent\' => 0,
                            \'post_type\' => \'attachment\',
                            \'post_mime_type\' => \'image/jpeg\'
              ));

     foreach ($media_query->posts as $post) {
          $fullpath = wp_get_attachment_url($post->ID);
      $list     = (explode("/", $fullpath));
      $string   = $post->ID.\'|\'.$list[sizeof($list)-1];

          if (substr($list[sizeof($list)-1],0,3) == \'UF-\') {
            array_push($data,(explode("|", $string)));
                $idx      = mt_rand(0, count($data)-1);
        $img_id   = $data[$idx][0];
          }
     }

     return $img_id;
}

add_action(\'the_post\', \'autoset_featured\');
add_action(\'save_post\', \'autoset_featured\');
add_action(\'draft_to_publish\', \'autoset_featured\');
add_action(\'new_to_publish\', \'autoset_featured\');
add_action(\'pending_to_publish\', \'autoset_featured\');
add_action(\'future_to_publish\', \'autoset_featured\');

1 个回复
最合适的回答,由SO网友:gmazzap 整理而成

首先,当你打电话给get_image 函数将post categories slugs作为参数传递。

Edit 你的autoset_featured 作用replacing

...
} else {
   set_post_thumbnail($post->ID, get_image());
}
...
使用:

... 
} else {
  $cat_slugs = wp_get_post_terms($post->ID, \'event-categories\', array("fields" => "slugs"));
  $image = get_image( $cat_slugs );
  if ( image ) set_post_thumbnail($post->ID, $image);
}
...
然后编辑get_image 对这样的事情:

function get_image( $cats = array() ) {
  $media_query = new WP_Query(
    array(
      \'post_status\' => \'inherit\',
      \'post_parent\' => 0,
      \'post_type\' => \'attachment\',
      \'post_mime_type\' => \'image/jpeg\',
      // set \'orderby\' to \'rand\' will randomize results order
      \'orderby\' => \'rand\',

      // READ CAREFULLY:
      // if in the title of all images intended to be used as thumbnail
      // you put something that contain \'UF\' you can use the \'s\' param
      // retrieving less results and so improving performance
      // in that case uncomment next line
      // \'s\' => \'UF\'

    )
  );

  if ( $media_query->have_posts() ) {

    $lastid = false; // just an early setup

    // loop through images
    foreach ($media_query->posts as $post) {

      // get current image url
      $fullpath = wp_get_attachment_url($post->ID);

      // if current image name doesn\'t start with \'UF-\' skip it
      if ( strpos( basename($fullpath), \'UF-\' ) !== 0 ) continue;

      // if the original post has no categories assigned, return first image ID
      // images are random ordered, so first one is random one
      if ( empty($cats) ) return $post->ID;    

      // get current image file name (without extension) and remove the \'UF-\' part
      $name = pathinfo( basename($fullpath), PATHINFO_FILENAME);
      $nameNoUF = str_replace(\'UF-\', \'\', $name); 

      // $nameNoUF contain something like \'category-name-01\'
      // because \'UF-\' at beginning and extension were both removed

      // save the current image ID in a helper variable for future possible use
      $lastid = $post->ID;

      // loop through categories and if $nameNoUF start with a category slug,
      // return the image ID.
      // this way every image named like \'UF-category-name-01.jpg\' match
      foreach ( $cats as $cat ) {
        if ( strpos($nameNoUF, $cat) === 0 ) return $post->ID;
      }
    }
    // if we are here no category related image was found, so return the last image ID
    // images are random ordered, so last one is random one
    return $lastid;
  }
  // no images found at all, sorry, return false (no thumbnail will be setted)
  return false;
}
按照内联注释中的建议,使用s 用于检索标题或内容中包含“UF”的图像以限制结果的查询中的参数。当然,这需要您将该字符串添加到图像标题或内容中。

内联注释应该解释函数的工作方式。

希望有帮助。

结束

相关推荐

Wp_Dropdown_Categories-删除 ;

我需要删除的自动添加&nbsp; 在wp_dropdown_categories, 这导致我使用的jQuery multi-select下拉插件出现问题。示例值:<option class=\"level-1\" value=\"120\">&nbsp;&nbsp;&nbsp;Apples&nbsp;&nbsp;(125)</option>