我有一个旧的WordPress网站。特色图片当时并不常见。所以我为缩略图编写了自定义代码。
现在我改变了主题,更新后的WordPress和精选图片是新主题的标准。
我想将为帖子上传的拳头(或任何)图片设置为帖子的精选图片。
我该怎么做?
感谢。
我想通了
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);
}
}
}
} //end function
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');
这个适合我。
答案 0 :(得分:1)
试试这个:
$args = array(
'post_type' => 'posts',
'numberposts' => -1,
);
$posts = get_posts($args);
foreach($posts as $post_temp){
$args = array(
'post_type' => 'attachment',
'numberposts' => 1,
'post_parent' => $post_temp->id,
'orderby' => 'post_date',
'order' => 'DESC'
);
$attachment = get_posts($args);
set_post_thumbnail( $post_temp->id, $attachment->id );
}