十一年专注,只做WordPress定制开发一件事

设置WordPress内容中的第一张图片作为特色图像

王超
2024-01-15
主题开发
220 次

之前我们有发布过一篇关于如何自动将WordPress内容中的第一张图片作为特色图像的教程,但是目前那个方法已经无效了,今天再分享一个最近刚亲测可以正常使用的方法。

我们只需要将以下代码添加到您的主题functions.php中,然后保存即可,不过这个只对新发布或者再次保存的文章有效果哦。且在代码中我们判断了,如果已经存在或者已经设置了文章的特色图像,那么就不再获取和设置了,如果内容中也没有图片,那就设置默认图片作为文章的特色图像,这个默认图像根据您的情况设置路径。

// 当文章没有设置特色图像时,提取内容中的第一张图片作为特色图像
function set_featured_image_from_content( $post_ID ) {
    $post = get_post( $post_ID );

    if ( ! has_post_thumbnail( $post_ID ) ) {
        $first_img = '';
        ob_start();
        ob_end_clean();
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
        $first_img = isset( $matches[1][0] ) ? $matches[1][0] : '';

        if ( empty( $first_img ) ) {
            // 定义默认图像
            $first_img = get_template_directory_uri() . "/default.jpg";
        }

        // 如果找到图片地址,则设置为特色图像
        if ( $first_img ) {
            $image_id = attachment_url_to_postid( $first_img );
            if ( $image_id ) {
                set_post_thumbnail( $post_ID, $image_id );
            }
        }
    }
}
add_action( 'save_post', 'set_featured_image_from_content' );

 

文章标签:

WordPress日记主要承接WordPress主题定制开发PSD转WordPressWordPress仿站以及以WordPress为管理后端的小程序、APP,我们一直秉持“做一个项目,交一个朋友”的理念,希望您是我们下一个朋友。如果您有WordPress主题开发需求,可随时联系QQ:919985494 微信:18539976310

搜索

嘿,有问题找我来帮您!