自动获取WordPress内容第一张图作为缩略图

目前,我们很多朋友都会用到的是自媒体博客主题,采用的是图文模式的。那势必每一篇文章都需要配置一张缩略图才会显示图片,否则留空没有图确实体验效果不好。有些朋友忘记或者不喜欢设置图,那我们有没有办法实现自动配图呢?一般我们会设置没有设置缩略图的时候会将当前文章的第一张图作为缩略图,那有办法设置?

function zhiku_automatic_featured_image( $post_id ) {
  if ( wp_is_post_revision( $post_id ) )
		return NULL;

	if ( ! isset( $post_id ) )
		return NULL;
	if ( has_post_thumbnail( $post_id ) )
		return NULL;

	$args = array(
		'numberposts'    => 1,
		'order'          => 'DESC', // DESC for the last image
		'post_mime_type' => 'image',
		'post_parent'    => $post_id,
		'post_status'    => NULL,
		'post_type'      => 'attachment'
	);

	$attached_image = get_children( $args );
	if ( $attached_image ) {
		foreach ( $attached_image as $attachment_id => $attachment )
			set_post_thumbnail( $post_id, $attachment_id );
	}
}
add_action( 'save_post', 'zhiku_automatic_featured_image' );

首先判断是不是自动保存的修订版本,然后判断当前编辑的是否为文章,最后判断是否手动设置了缩略图,如果都不是,调取文章附件中的第一张图片,设置为文章的缩略图。

代码参考来自:https://www.wpzhiku.com/automatic-set-featured-imahes/

投票 post
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享