• <form id="qodvc"></form>
  • <button id="qodvc"></button>
  • <th id="qodvc"></th>
  • 也想出现在这里?联系我们

    WordPress文章自动设置特色图像

    2022.09.02 wordpress教程
    • 文章介绍
    • 升级版本
    • 评价&建议

    介绍目前WordPress文章自动设置特色图像的方法。WordPress的特色图像是一个很实用的功能,为每篇文章增加一个特色图像,可以使blog各个部分都更生动。比如首页每篇文章都有自己的缩略图,相关文章中用缩略图告诉用户这些文章的主题,或者在侧栏加一个特色文章功能,显示文章特色图像。

    现在的情况是,发布的文章,并插入了图像后,不显示缩略图,原因是the_post_thumbnail需要设置特色图像,而大多情况是懒得一一设置。

    那么使用下面的代码吧,直接自动化为文章内的图像自动设置为特色图像

    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页面等等。好处是被人访问一段时间,你的所有文章就自动获得了特色图像,坏处就是对性能有影响。当你的特色图像设置的差不多时,应该将这一句注释掉。

    有用4
    • 2022.09.02初次和大家见面了!

    等待您对该主题的建议

    发表评论

    还能输入240个字

    Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

    我要入群
    也想出现在这里?联系我们
    wordpress加速

    我来推荐一个更牛逼的给你看看?

    • 猛戳我吧
    亚洲中文av一区二区三区
  • <form id="qodvc"></form>
  • <button id="qodvc"></button>
  • <th id="qodvc"></th>