首先,当你打电话给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”的图像以限制结果的查询中的参数。当然,这需要您将该字符串添加到图像标题或内容中。
内联注释应该解释函数的工作方式。
希望有帮助。