WordPress:自定义简码以使用元数据渲染图像

时间:2019-04-07 21:27:24

标签: wordpress shortcode

我的问题:如何在PHP中将媒体数据从数据库中拉出

我想编写一个短代码,以使用从媒体数据库自动获取的alt文本和标题渲染图像。用法示例:

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

预期输出:

  

Demo image

     

数据库字幕

1 个答案:

答案 0 :(得分:0)

我希望通过一些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'是图片的替代文字

我们并不需要所有这些,因为确实有一些帮助函数,使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>