本文档介绍了WordPress中媒体功能的核心概念,包括媒体的上传、存储和显示方式,以及如何通过代码检索附件ID或图像ID。面向主题开发者,帮助自定义平台的媒体能力。
// Insert into the Loop
$args = array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$meta_data = wp_get_attachment_metadata( $attachment->ID, false );
}
}WordPress enables theme developers to customize the look, feel, and functionality of the platform’s core media capabilities.
In WordPress you can upload, store, and display a variety of media such as image, video and audio files. Media can be uploaded via the Media > Add New in the Administration Screen, or Add Media button on the Post/Page Editor.
If a media file is uploaded within the edit screen, it will be automatically attached to the current post being created or edited. If it is uploaded via the Media’s Add New Screen or the Media Library Screen, it will be unattached, but may become attached to a post when it is inserted into a post later on.
To retrieve the attachment ID, use <a href="https://developer.wordpress.org/reference/functions/get_posts/">get_posts()</a> or <a href="https://developer.wordpress.org/reference/functions/get_children/">get_children()</a> function. This example retrieves the all attachments of the current post and getting all metadata of attachment by specifying the ID.
// Insert into the Loop
$args = array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$meta_data = wp_get_attachment_metadata( $attachment->ID, false );
}
}
If you want to retrieve images from the post ID only, specify post_mime_type as image.
$args = array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'post_mime_type' => 'image',
);
<a href="https://developer.wordpress.org/reference/functions/get_posts/">get_posts()</a><a href="https://developer.wordpress.org/reference/functions/get_children/">get_children()</a><a href="https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/">wp_get_attachment_metadata()</a>In the Media Library, you can upload any file (with the network administrator’s unfiltered_upload) and not just images or videos but text files, office documents or even binary files. Single site administrators do not have the unfiltered_upload capability by default and requires that definition to be set for the capability to kick in. Audio and Video files are processed by the internal library MediaElement.js.
When you cannot get your attached media by <a href="https://developer.wordpress.org/reference/functions/get_posts/">get_posts()</a> or <a href="https://developer.wordpress.org/reference/functions/get_children/">get_children()</a> function, confirm your media is really attached to the post.
From the Administration Screen, Click Media > Library to open the Media Library and confirm the value in “Uploaded to” column of the media.