Plugin Name: GD Title Image Generator

  • Plugin Name: GD Title Image Generator
  • Description: Generates an image using PHP GD with the post title and sets it as the featured image.
  • Version: 1.0
  • Author: Your Name
    */

add_action(‘save_post’, ‘gdtig_generate_featured_image’);

function gdtig_generate_featured_image($post_id) {
// Avoid recursion or invalid post
if (wp_is_post_revision($post_id)) return;
$post = get_post($post_id);
if ($post->post_type !== ‘post’) return;
if (has_post_thumbnail($post_id)) return;

// Get the post title
$title = get_the_title($post_id);

// Background image from Media Library
$bg_image_id = 123; // Replace with your Media Library image ID
$bg_path = get_attached_file($bg_image_id);
if (!file_exists($bg_path)) return;

// Load background image using GD
$image = imagecreatefromjpeg($bg_path);

// Setup text options
$white = imagecolorallocate($image, 255, 255, 255);
$font_path = plugin_dir_path(__FILE__) . 'font/OpenSans-Bold.ttf';
$font_size = 32;

// Image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);

// Center the title horizontally
$bbox = imagettfbbox($font_size, 0, $font_path, $title);
$text_width = $bbox[2] - $bbox[0];
$x = ($image_width - $text_width) / 2;
$y = $image_height / 2;

// Write the title onto the image
imagettftext($image, $font_size, 0, $x, $y, $white, $font_path, $title);

// Save the image in uploads/generated/
$upload_dir = wp_upload_dir();
$generated_dir = $upload_dir['basedir'] . '/generated';
if (!file_exists($generated_dir)) {
    mkdir($generated_dir, 0755, true);
}

$filename = 'post-' . $post_id . '-' . time() . '.jpg';
$file_path = $generated_dir . '/' . $filename;
imagejpeg($image, $file_path, 90);
imagedestroy($image);

// Register the image in the Media Library
$file_url = $upload_dir['baseurl'] . '/generated/' . $filename;
$attachment = [
    'guid' => $file_url,
    'post_mime_type' => 'image/jpeg',
    'post_title' => sanitize_file_name($filename),
    'post_content' => '',
    'post_status' => 'inherit'
];
$attach_id = wp_insert_attachment($attachment, $file_path, $post_id);

require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);

// Set as featured image
set_post_thumbnail($post_id, $attach_id);

}

Leave a Comment