我正在尝试使用此方法获取帖子的所有图片:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images;
}
不幸的是,这将使所有图像上传,而不仅仅是与当前帖子相关的图像。我发现这个post使用* get_children *,但它也不起作用。任何想法?
ps:我在创建/更新帖子时运行代码
答案 0 :(得分:4)
你可以尝试
<?php
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
?>
了解更多here。
确保$ post-&gt; ID不为空。 如果仍然无效,您可以尝试从页面/帖子内容中提取图像。更多详情here
答案 1 :(得分:1)
在创建/更新帖子/页面后,在functions.php
中添加一个钩子,然后将其包装在该函数内,如下所示
add_action( 'save_post', 'after_post_save' );
function after_post_save( $post_id ) {
if ( 'post' == get_post_type($post_id) ) // check if this is a post
{
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post_id
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images; // End of function and nothing happens
}
}
}
请记住,除非您对图片执行某些操作,否则在函数末尾返回$images
数组基本上不会做任何事情。
注意: wp_get_attachment_image_src
函数返回一个包含
[0] => url // the src of image
[1] => width // the width
[2] => height // the height
因此,在$images
数组中,它将包含类似
array(
[0] => array([0] => url, [1] => width, [2] => height), // first image
[1] => array([0] => url, [1] => width, 2] => height) // second image
);