Wordpress:自定义短代码,用于使用元数据渲染图像

问题描述 投票:0回答:1

我的问题:如何在PHP中从数据库中提取媒体数据?

我想写一个短代码,用于从媒体数据库中自动呈现带有alt文本和标题的图像。用法示例:

[img 126 300]  // [img media-id width]

预期产出:

Demo image

来自数据库的标题

wordpress shortcode
1个回答
0
投票

我希望有一些wordpress-integrated函数能够在几行代码中获得所需的值,但是使用@ disinfor的提示我在wordpress数据库中挖了一下并得出以下结果。

首先概述如何在Wordpress数据库中保存图像及其元数据:

  • wp_posts.post_title是图像的标题
  • wp_posts.post_excerpt是图像的标题
  • wp_posts.guid是图像的网址
  • wp_posts.post_content是图像媒体页面的内容
  • wp_postmeta.meta_value WHERE meta_key='_wp_attachment_image_alt'是图像的替代文字

我们不需要所有这些因为确实有一些辅助函数可以更容易地创建我们自己的图像短代码,即wp_get_attachment_imageimg_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>
© www.soinside.com 2019 - 2024. All rights reserved.