Reputation: 6223
My problem: How to pull the media data out of the database in PHP?
I'd like to write a shortcode that renders an image with the alt-text and caption taken automatically from the media database. Usage-example:
[img 126 300] // [img media-id width]
Intended Output:
Caption from Database
Upvotes: 1
Views: 1713
Reputation: 6223
I was hoping for some wordpress-integrated function to get me the needed values in a few lines of code, but with @disinfor's hint I dug a bit into the wordpress database and came to the following results.
First an overview how an image and its metadata are saved in the Wordpress database:
wp_posts.post_title
is the title of the imagewp_posts.post_excerpt
is the caption of the imagewp_posts.guid
is the url of the imagewp_posts.post_content
is the content of the image's media pagewp_postmeta.meta_value WHERE meta_key='_wp_attachment_image_alt'
is the alt-text of the imageWe don't need all of them since there indeed are some helper functions that make creation of our own image shortcode easier, namely wp_get_attachment_image
and img_caption_shortcode
.
Code below (I've extended the shortcode to also give an arbitrary class to the image):
function img_shortcode($atts) {
// Signature: [img <media_id> <width> <classes>], i.e. [img 126 300 "article-image"]
// You may pass other keyword-attributes accepted from `img_caption_shortcode`
// except 'class'. You can even override 'caption' manually
global $wpdb;
try {
$conn = new \PDO("mysql:host=" . constant('DB_HOST') . ";dbname=" . constant('DB_NAME'), constant("DB_USER"), constant("DB_PASSWORD"));
// set the PDO error mode to exception
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
#echo "Connected successfully";
$sql = "SELECT post_excerpt FROM `". $wpdb->prefix . "posts` WHERE ID=". $atts[0] ."";
$stmt = $conn->prepare($sql);
$stmt->execute();
$caption = $stmt->fetch(\PDO::FETCH_ASSOC)['post_excerpt'];
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
return NULL;
}
$a = shortcode_atts([
'width' => $atts[1],
'caption' => $atts['caption'] ? $atts['caption'] : $caption,
'class' => $atts[2],
], $atts, 'img');
$html = '<div class="image-container">';
$html .= wp_get_attachment_image($atts[0], [$atts[1]], false, $a['class'] ? ["class" => $a['class']] : '');
$html .= img_caption_shortcode($a);
$html .= '</div>';
return $html;
}
add_shortcode('img', 'img_shortcode');
It will output the following structure:
<div class="image-container">
<img src="https://www.example.com/path-to-image.jpg" class="article-image" alt="alt-text from db" srcset="...all image-sizes from db" sizes="(max-width: 600px) 100vw, 600px" width="600" height="395">
<div style="width: 610px" class="wp-caption alignnone article-image">
<p class="wp-caption-text">The Captiontext</p>
</div>
</div>
Upvotes: 1