Skip to content

Instantly share code, notes, and snippets.

@clifgriffin
Last active January 5, 2022 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clifgriffin/753c9560a74715589ebc to your computer and use it in GitHub Desktop.
Save clifgriffin/753c9560a74715589ebc to your computer and use it in GitHub Desktop.
<?php
// autofit_text_to_image() WordPress example
// http://cgd.io/2014/auto-fit-text-to-an-image-with-php-and-wordpress
$canvas_image_filename = 'quote_canvas.png';
$dest_filename = trailingslashit($upload_dir['path']) . "featured_image_{$post->ID}.jpg";
$text = 'I believe in pink. I believe that laughing is the best calorie burner. I believe in kissing, kissing a lot.';
$font_file = 'Cedarville-Cursive.ttf';
$result = autofit_text_to_image($canvas_image_filename, $dest_filename, $text, 60, 500, 400, 40, 400, $font_file);
if ($result) {
$upload_dir = wp_upload_dir();
$filetype = wp_check_filetype( basename( $dest_filename ), null );
$attachment = array(
'guid' => $upload_dir['url'] . '/' . basename( $dest_filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $dest_filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$new_attachment = wp_insert_attachment( $attachment, $dest_filename, $post->ID );
$attach_data = wp_generate_attachment_metadata( $new_attachment, $dest_filename );
wp_update_attachment_metadata( $new_attachment, $attach_data );
update_post_meta($post->ID, '_thumbnail_id', $new_attachment);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment