Need help figuring out how to add dynamic image from data/topic posts

Ben
Need help figuring out how to add dynamic image from data/topic posts
Ben@e45e27cd Friday 6th October 2023, 02:14:58

If anyone with php knowledge can help I would sure appreciate it. I would like to create a dynamic meta og:image tag to add to the header.tpl.php file to extract the post image dynamically from each post.

Here's what happens now, anytime I share a post across social media, it shows the correct post image, but the moment it's posted as a new standalone post it takes the larger image from the post, and replaces it with a thumbnail image named flatboard.png image.

Yet if I respond to a post on Facebook, it adds the correct image as a thumbnail sized image and this works perfectly.

Have tried countless things and am getting nowhere. If anyone has any ideas, could really use some help.

Reply 1
Ben
Ben@84171e7c  Saturday 7th October 2023, 15:20:26

Figured this out! Now posts correctly share the jpg image on Facebook instead of the default flatboard.png image. If you want to fix your forum code add this loop to your header.tpl.php file and it will output an og:image meta tag which Facebook algo will then choose as the correct image for each post. This assumes the post image is in jpg format.

<?php
if ($cur === 'viewTopic' && isset($out['content'])) {

// Extract the file ID from the URL
$url_parts = explode('/', $_SERVER['REQUEST_URI']);
$file_id = end($url_parts);

if ($file_id) {
$file_path = "data/topic/{$file_id}.dat.php";

// Check if the file exists and is readable
if (file_exists($file_path) && is_readable($file_path)) {
// Read the file content
$file_content = file_get_contents($file_path);

// Extract the first URL ending with .jpg or .jpeg
preg_match('/(https?:\/\/[^\s]*\.(?:jpg|jpeg))/', $file_content, $image_matches);
$image_url = isset($image_matches[1]) ? $image_matches[1] : '';

if ($image_url) {
echo '<meta property="og:image" content="' . $image_url . '" />';
}
} else {
echo '<!-- File not found or not readable -->';
}
} else {
echo '<!-- No File ID found -->';
}
}
?>

Last modified by Ben@84171e7c on Saturday 7th October 2023, 15:21:00

Suggested Topics
Yhellothar
Yhellothar@84618b92 started Hiya everyone
Open Bar
24.6K 5
Want to read more? Browse all categories or view latest topics.