如何从媒体库中获取随机图像的标题?

时间:2016-04-20 作者:Ruby Ann Rosales

我在我的主页中显示随机图像。我的问题是,我无法获取要在lightbox中显示的图像的标题。

这是我的密码。

从媒体库获取图像的代码

function get_images_from_media_library() {
    $args = array(
        \'post_type\' => \'attachment\',
        \'post_mime_type\' =>\'image\',
        \'post_status\' => \'inherit\',
        \'posts_per_page\' => 6,
        \'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 class="no-gutter">\';

    foreach($imgs as $img) {
            $html .= \'<div class="col-lg-4 col-sm-6 photo-gallery">
            <a class="portfolio-box" data-lightbox="out-of-the-box" data-title="\' . $attachment->post_title . \'" href="\' . $img . \'"><img src="\' . $img . \'" alt="" />
                <div class="portfolio-box-caption">
                    <div class="portfolio-box-caption-content">
                        <div class="project-category text-faded">
                            View <i class="fa fa-search-plus"></i>
                        </div>
                    </div>
                </div>
            </a></div>\';
    }

    $html .= \'</div>\';

    return $html; } ?>
希望你能帮助我。

1 个回复
SO网友:Pierrick

您的第一个函数get\\u images\\u from\\u media\\u library()只返回图像guid,我建议通过返回所有图像数据来扩展它:

function get_images_from_media_library() {
    $args = array(
        \'post_type\' => \'attachment\',
        \'post_mime_type\' =>\'image\',
        \'post_status\' => \'inherit\',
        \'posts_per_page\' => 6,
        \'orderby\' => \'rand\'
    );
    $query_images = new WP_Query( $args );
    $images = array();
    foreach ( $query_images->posts as $image) {
        $images[]= $image;
    }
    return $images;
}
然后,在第二个函数中,获得所需内容(guid和标题),如下所示:

function display_images_from_media_library() {
    $imgs = get_images_from_media_library();
    $html = \'<div class="no-gutter">\';
    foreach($imgs as $img) {
        $html .= \'<div class="col-lg-4 col-sm-6 photo-gallery">
            <a class="portfolio-box" data-lightbox="out-of-the-box" data-title="\' . esc_attr($img->post_title) . \'" href="\' . $img->guid . \'"><img src="\' . $img->guid . \'" alt="" />
                <div class="portfolio-box-caption">
                    <div class="portfolio-box-caption-content">
                        <div class="project-category text-faded">
                            View <i class="fa fa-search-plus"></i>
                        </div>
                    </div>
                </div>
            </a>
        </div>\';
    }
    $html .= \'</div>\';
    return $html;
}
别忘了用转义HTML和引号esc_attr() 在HTML属性上发送文本值时(例如“标题”、“数据标题”…)避免引号冲突或以纯文本形式呈现的HTML标记;)

干杯

相关推荐

Dash after page title

在“中”;“页码”;在WordPress管理面板的一节中,在一些页面标题之后,我看到了这些长划线和一个类似的注释:;隐私政策页面"E;首页,Elementor“;,等这些是什么;注释</如何编辑它们