我希望有一些与 wordpress 集成的功能,可以在几行代码中获得所需的值,但在 @disinfor 的提示下,我对 wordpress 数据库进行了一些研究,得出了以下结果。
首先概述图像及其元数据如何保存在 Wordpress 数据库中:
-
wp_posts.post_title 是图片的标题
-
wp_posts.post_excerpt 是图片的标题
-
wp_posts.guid 是图片的url
-
wp_posts.post_content 是图片媒体页面的内容
-
wp_postmeta.meta_value WHERE meta_key='_wp_attachment_image_alt' 是图片的alt-text
我们不需要所有这些,因为确实有一些帮助函数可以更轻松地创建我们自己的图像短代码,即wp_get_attachment_image 和img_caption_shortcode。
下面的代码(我已经扩展了简码,也给图像一个任意类):
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');
它将输出以下结构:
<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>