我正在尝试获取一个帖子中附加图像的图像id。我在举个例子posted here, 但是,我很难只返回ID,而不是整个数组。
我的目标是返回一个以逗号分隔的附加图像ID列表。
1, 2, 3, 4, 5
以下是我的功能:
function wpse_get_images() {
global $post;
$id = intval( $post->ID );
$size = \'medium\';
$attachments = get_children( array(
\'post_parent\' => $id,
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order\'
) );
if ( empty( $attachments ) )
return \'\';
$output = "\\n";
/**
* Loop through each attachment
*/
foreach ( $attachments as $id => $attachment ) :
$title = esc_html( $attachment->post_title, 1 );
$img = wp_get_attachment_image_src( $id, $size );
$imgID = wp_get_attachment_metadata( $attachment_id );
$imgID = (string)$imgID;
$output .= $imgID->$attachment_id.\', \'; // prints: 1,2,3,4,5,6,8,9,
endforeach;
return $output;
}
SO网友:birgire
您可以在循环中尝试此一行程序,而不是上面的所有代码:
$ids = join( \',\', wp_list_pluck( get_attached_media(\'image\' ), \'ID\' ) );
我们从
get_attached_media()
输出
另一种方法是使用:
$ids = join( \',\', get_attached_media( \'_image_ids\' ) );
我们引入了一个新的输入参数
_image_ids
, 使用以下插件支持:
/**
* Plugin Name: Enhance the get_attached_media() function.
* Description: Support for the custom \'_image_ids\' parameter.
* Plugin URI: http://wordpress.stackexchange.com/a/169152/26350
* Author: birgire
* Version: 0.0.1
*/
add_filter( \'get_attached_media_args\', function( $args, $type, $post ) {
if( \'_image_ids\' === $type )
{
$args[\'post_mime_type\'] = \'image\';
$args[\'fields\'] = \'ids\';
}
return $args;
}, 10, 3 );