从Wordpress媒体库中获取单个特定图像

 Dr_H-鄧 发布于 2023-02-09 13:40

我已将图像上传到Wordpress媒体库.

我知道我可以查看我的图像,然后获取该特定图像的URL,然后使用imghtml标签在页面上显示.

然而,这并不得到alt,title,captiondescription图像.

img没有连接到一个帖子或网页领域,所以我想你不能使用Get附加功能等.

我想使用函数而不是编写静态imghtml代码的原因是,它们被缓存得更好,更容易维护,图像的所有数据都在媒体库中更新,而不必编辑不想法的HTML代码为最终用户.

先感谢您.

2 个回答
  • 我猜你有附件ID?你尝试过使用附件功能吗?

    来自法典:

    请注意,媒体项目本身也是"帖子",可以通过WordPress模板层次结构显示.主题可以利用它来循环媒体项目或创建画廊.

    以下功能可以帮助您入门:

    您可以使用以下命令检索图像src:wp_get_attachment_image_src()

    $img= wp_get_attachment_image_src($attachmentID, $imageSizeName); 
    

    你可以使用以下方法获取图片标题:get_post_field()

    get_post_field('post_excerpt', $attachmentID)
    

    你可以使用:get_post_meta()获得alt标签

    get_post_meta($attachmentID, '_wp_attachment_image_alt', true);
    

    2023-02-09 13:43 回答
  • 先得到图像

    function get_images_from_media_library() {
        $args = array(
            'post_type' => 'attachment',
            'post_mime_type' =>'image',
            'post_status' => 'inherit',
            'posts_per_page' => 5,
            'orderby' => 'rand'
        );
        $query_images = new WP_Query( $args );
        $images = array();
        foreach ( $query_images->posts as $image) {
            $images[]= $image->guid;
        }
        return $images;
    }
    

    并显示图像

    function display_images_from_media_library() {
    
        $imgs = get_images_from_media_library();
        $html = '<div id="media-gallery">';
    
        foreach($imgs as $img) {
    
            $html .= '<img src="' . $img . '" alt="" />';
    
        }
    
        $html .= '</div>';
    
        return $html;
    
    }
    

    并使用php fire事件

    <?php echo display_images_from_media_library(); ?>
    

    或使用此功能

    <?php
    
    if ( $attachments = get_children( array(
    'post_type' => 'attachment',
    'post_mime_type'=>'image',
    'numberposts' => 1,
    'post_status' => null,
    'post_parent' => $post->ID
    )));
    foreach ($attachments as $attachment) {
    echo wp_get_attachment_link( $attachment->ID, '' , true, false, 'Link to image attachment' );
    }
    
    ?>
    

    2023-02-09 13:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有