wordpress自动设置文章第一张图为特色图

下面这段代码会将文章中第一张WordPress附件图片设置为特色图像,附件图片是指上传到WordPress的图片,不需要和当前的文章有关联。

function sola_auto_featured_image() {
  global $post;

  if( has_post_thumbnail() ){
    return;
  }

  preg_match('/<img\s[^>]*?class\s*=\s*[\'\"]([^\'\"]*?)[\'\"][^>]*?>/', $post->post_content, $matches);
  $img_class = $matches[1] ?? false;

  if( $img_class ){
    preg_match('/wp-image-([\d]+)/', $img_class, $matchId);
    $attachment_id = $matchId[1] ?? false;

    if( $attachment_id ){
        set_post_thumbnail($post->ID, absint($attachment_id) );
    }
  }
}

add_action('the_post', 'sola_auto_featured_image');
add_action('save_post_post', 'sola_auto_featured_image');

注意:add_action(‘the_post’, ‘sola_auto_featured_image’)会使这段代码在任何文章被加载时运行,比如archive页面,single post页面等等。好处是被人访问一段时间,你的所有文章就自动获得了特色图像,坏处就是对性能有影响。当你的特色图像设置的差不多时,应该将这一句注释掉。

原文链接:https://www.solagirl.net/automatically-set-the-featured-image-in-wordpress.html

本文链接: https://www.168itw.com/wordpress/featured-img/
转载请注明转载自:168itw

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注