【wordpress教程】免插件自动为文章国外主题添加特色图像 逍遥乐教程

使用的童鞋都知道,它们不像国内主题,都是自动缩略图!因为外国人崇尚自由,国外主题都需要手动设置缩略图!设置wordpress的特色图像在很多时候还是挺不错的,不过比较麻烦的是需要用户手动选择设置,但我们不是每次都能想起来点一下设置特色图像按钮的,所以手动选择设置wordpress特色图像就显得有些不方便了,如果能自动为WordPress文章添加特色图像,就方便多了。 

今天逍遥乐就给大家带了两段代码!,可以自动将文章中的第一张图片设置为特色图像,如果你手动设置了特色图像,这段代码自动对当前文章无效。将下面的代码复制到主题的functions.php结束语句前,就能解决!

为了方便大家给出演示,以我所汉化sahifa举例吧!ftp下载主题下根目录的functions.php(注:不是主题文件夹中functions文件夹中的,是sahifa主题文件夹根目录),一下以下是代码示例,图中用的是第一个代码,2个代码有所不同,大家各取所需

【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 function
add_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, '513');
                           }
                        }
      }  //end function
add_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');

 

看以上代码和第一段代码有了一些差别,多了个

else { set_post_thumbnail($post->ID, '513'); } 

我们需要将ID后引号中的数字改为我们上传的图片ID!这张图片将作为文章中没有图片时自动设置特色图片的图片! 图片ID在哪儿找呢!方法是:网站后台-多媒体-媒体库 将鼠标移动到你要设置的图片,即可看见ID!也可以编辑图片,进入编辑界面,在图片地址上可以看见!以下给出截图说明:


【wordpress教程】免插件自动为文章国外主题添加特色图像 逍遥乐教程

好了就这么多!你们看清楚了吗?如果觉得麻烦就用第一个,如果不想麻烦而且想要更加智能的话,就选择第二个代码! 以上代码均通过本人本地测试无误!确认有效!

好了感谢大家对逍遥乐的支持!谢谢大家!

如果大家觉得可以的话记得在文章下方评论!谢谢!