WordPress 网站自动为文章添加特色图像

编程入门 行业动态 更新时间:2024-10-07 12:19:34

WordPress 网站自动为文章添加特色<a href=https://www.elefans.com/category/jswz/34/1771430.html style=图像"/>

WordPress 网站自动为文章添加特色图像

WordPress 网站怎么自动为文章添加特色图像?WordPress的特色图像是一个很实用的功能,可以在文章列表中为每篇文章添加一张缩略图。但特色图像需要在编辑文章时手动添加很不方便,下面的代码可自动将文章中的第一张图片设置为特色图像。主机教程网给大家详细讲一下。

1、将下面的代码添加到当前主题的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');  

2、如果当前文章中没有图片,但又想显示一张默认的缩略图该怎么办,可以将上面的代码修改一下,调用媒体库中某个图片作为默认的缩略图:

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');  

3、其中的数字414,是媒体库中某个图片附件的ID号。

4、说明:上面的代码只是一篇技术文章,可能会影响到之前添加的特色图像,所以不要轻易在自己的网站上做试验。特色图像只适合不在乎空间流量和大小的用户使用,因为每张图片都会裁剪成多张大小不同的缩略图方便在不同的位置调用,最主要的是不支持外链,很浪费空间。

  • 由 主机教程网 发表于 主机教程网
  • 热门推荐:腾讯云优惠券 阿里云代金券 腾讯云百科 腾讯云 云服务器
  • 原文链接:.html

更多推荐

WordPress 网站自动为文章添加特色图像

本文发布于:2024-03-06 16:35:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1715811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   特色   文章   网站   WordPress

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!