第一獲取圖像
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的火災事件
<?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');
}
?>
這個答案對我的作品最好,謝謝。 –
但是你在哪裏獲得附件的實際ID? – Philip
當您在媒體庫中查看圖像時,您可以在瀏覽器欄的URL中看到附件ID。 – Tamara