WordPress教程 WordPress自动文章添加特色图片教程

WordPress的特色图像是一个很实用的功能,可以在文章列表中为每篇文章添加一张缩略图。但特色图像需要在编辑文章时手动添加很不方便,下面的代码可自动将文章中的第一张图片设置为特色图像。

将下面的代码添加到当前主题的functions.php中:

function wpforce_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 functionadd_action('the_post', 'wpforce_featured');add_action('save_post', 'wpforce_featured');add_action('draft_to_publish', 'wpforce_featured');add_action('new_to_publish', 'wpforce_featured');add_action('pending_to_publish', 'wpforce_featured');add_action('future_to_publish', 'wpforce_featured');
如果当前文章中没有图片,但又想显示一张默认的缩略图该怎么办,可以将上面的代码修改一下,调用媒体库中某个图片作为默认的缩略图:

function wpforce_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, '414');}}}  //end functionadd_action('the_post', 'wpforce_featured');add_action('save_post', 'wpforce_featured');add_action('draft_to_publish', 'wpforce_featured');add_action('new_to_publish', 'wpforce_featured');add_action('pending_to_publish', 'wpforce_featured');add_action('future_to_publish', 'wpforce_featured');
其中的数字414,是媒体库中某个图片附件的ID号。

提示

上面的代码只是一篇技术文章,可能会影响到之前添加的特色图像,所以不要轻易在自己的网站上做试验。

特色图像只适合不在乎空间流量和大小的用户使用,因为每张图片都会裁剪成多张大小不同的缩略图方便在不同的位置调用,最主要的是不支持外链,很浪费空间....

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值