Wordpress:获取当前帖子的图片



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

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

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

ps:i在后创建/更新时运行代码

您可以尝试

<?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不为空。如果这仍然不起作用,您可以尝试从页面/帖子内容中提取图像。更多详细信息,请点击此处

试着在你的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
);

相关内容

  • 没有找到相关文章

最新更新