如何从帖子中抓取所有附件[视频,图像]并在UL模板中显示

时间:2013-12-17 18:05:34

标签: wordpress

我写了一些代码,在UL中显示所有附件图像,以便在自定义帖子类型上进行旁边滚动。客户现在也想要视频返回。现在,我正在使用正则表达式来解析帖子中的所有图像,但它并没有抓取视频。另外,我讨厌取决于正则表达式,因为现在的实现也不可能获取url等。

有没有办法获取与帖子相关联的所有附件(不包括自定义字段缩略图),然后在页面上的元素中填充附件?

1 个答案:

答案 0 :(得分:0)

这将调用所有附件类型 - 只需为其他mime类型添加额外的语句(png,gif等)。

    <?php 
$thumb_ID = get_post_thumbnail_id( $post->ID );
$attachments = get_posts(array(
        'post_parent' => $post->ID,
        'post_type' => 'attachment',
        'numberposts' => -1,
        'orderby'        => 'title',
        'order'           => 'ASC',
        'exclude' => $thumb_ID,
    ));

if ( $attachments ) {   
foreach( $attachments as $attachment ) {
    $attachment_mime = wp_check_filetype(wp_get_attachment_url($attachment->ID) );
            $title = apply_filters( 'the_title' , $attachment->post_title );
            if ( $attachment_mime['type'] == 'image/jpeg') {echo '<li><img src="' . wp_get_attachment_url( $attachment->ID ) . '" alt="'.$title.'"  /></li>'; }
            elseif( $attachment_mime['type'] == 'video/mp4'){echo '<li><video class="video-js vjs-default-skin" controls data-setup="{}"><source src="'.wp_get_attachment_url( $attachment->ID ).'" type="video/mp4" /></video></li>';}           
}
}?>