function generate_letter_image() {
if (is_single()) {
$title = get_the_title();
$first_letter = strtoupper($title[0]);
$r = rand(0, 255);
$g = rand(0, 255);
$b = rand(0, 255);
$image = imagecreatetruecolor(150, 150);
$background = imagecolorallocate($image, $r, $g, $b);
imagefill($image, 0, 0, $background);
$text_color = imagecolorallocate($image, 255, 255, 255); // White color for the letter
// Path to the Montserrat font
$font_path = get_stylesheet_directory() . '/fonts/Montserrat-SemiBold.ttf'; // Make sure this path is correct
// Font size adjustment and text placement logic here
$font_size = 100;
$bbox = imagettfbbox($font_size, 0, $font_path, $first_letter);
$text_width = $bbox[2] - $bbox[0];
$text_height = $bbox[1] - $bbox[7];
while ($text_width > 125 || $text_height > 125) {
$font_size -= 5;
$bbox = imagettfbbox($font_size, 0, $font_path, $first_letter);
$text_width = $bbox[2] - $bbox[0];
$text_height = $bbox[1] - $bbox[7];
}
$x = (150 - $text_width) / 2;
$y = (150 - $text_height) / 2 + $text_height;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_path, $first_letter);
$upload_dir = wp_upload_dir();
$filename = 'letter_image_' . get_the_ID() . '.png';
$filepath = $upload_dir['path'] . '/' . $filename;
if (imagepng($image, $filepath)) {
imagedestroy($image);
return '';
} else {
imagedestroy($image);
return 'Failed to save image.';
}
}
return 'Applicable only within a single post.';
}
function display_letter_image_shortcode() {
return generate_letter_image();
}
add_shortcode('letter_image', 'display_letter_image_shortcode');