1

我正在尝试使用此方法获取帖子的所有图像:

$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;
    }

不幸的是,这将获取所有上传的图像,而不仅仅是与当前帖子相关的图像。我使用 *get_children* 找到了这篇文章,但它也不起作用。有任何想法吗?

ps:我在创建/更新帖子时运行代码

4

2 回答 2

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>';
            }

        }

?>

在这里阅读更多。

确保 $post->ID 不为空。如果这仍然不起作用,您可以尝试从页面/帖子内容中提取图像。更多细节在这里

于 2012-09-01T20:08:29.970 回答
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
);
于 2012-09-01T20:31:33.000 回答