Join the Voxel Guide Community!

Get Involved

Generate Default Image for Posts

Description/Instructions

This snippet mimics what Facebook pages does. When you first create a page, it fills the profile image with an image with the first letter of the business name with a random color as the background. This is to encourage the user to upload an image as their profile picture. This snippet mimic that functionality. Great for when importing posts, and you don’t want them all to have the same default picture.

Be sure to download the associated file, unzip and put it in the voxel child theme directory in the same root as the functions.php file. 

Associated Files

If this snippet helped, feel free to buy me a taco :)

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 'Post Letter Image';
} 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');

  • PHP
Copy Code

Instructions

Shortcode to add to the single post template. Be sure to use conditionals to show if the profile is empty, and vice versa to hide the profile if empty too

[letter_image]

  • HTML
Copy Code

Let's Chat About this Snippet