WordPress如何自动给文章添加特色图像

追格官方小助手/ 2022年04月13日/ WordPress/ 浏览 1453

之前追格小程序小编写过一篇《WordPress批量移除所有文章的特色图片方法》,而今天要讲的是,如何自动给文章添加特色图像,有时候偷懒懒得设置,有没有什么办法,直接获取正文中的第一张图为特色图像。


不妨看看小编是怎么操作的,先看效果图:



WordPress主题functions.php文件至下方的“?>”前,加入以下PHP代码即可。


if ( ! function_exists( 'fb_set_featured_image' ) ) {
    
    add_action( 'save_post', 'fb_set_featured_image' );
    function fb_set_featured_image() {
            
            if ( ! isset( $GLOBALS['post']->ID ) )
                return NULL;
                
            if ( has_post_thumbnail( get_the_ID() ) )
                return NULL;
            
            $args = array(
                'numberposts'    => 1,
                'order'          => 'ASC', // DESC for the last image
                'post_mime_type' => 'image',
                'post_parent'    => get_the_ID(),
                'post_status'    => NULL,
                'post_type'      => 'attachment'
            );
            
            $attached_image = get_children( $args );
            if ( $attached_image ) {
                foreach ( $attached_image as $attachment_id => $attachment )
                    set_post_thumbnail( get_the_ID(), $attachment_id );
            }
            
    }
    
}



发表评论

暂无评论,抢个沙发...

客服 工单