【问题标题】:Displaying all images from a WordPress post (including media library)显示来自 WordPress 帖子的所有图像(包括媒体库)
【发布时间】:2023-01-07 04:30:51
【问题描述】:

使用此功能,我只能获取使用帖子部分中的上传按钮上传的那些图像。 但是,如果我从媒体库中添加一张图片,它就会显示出来。我想显示帖子中的所有图片。

如何显示帖子中的所有图片?

$attachments = get_children(array('post_parent' => $post->ID,
              'post_status' => 'inherit',
              'post_type' => 'attachment',
              'post_mime_type' => 'image',
              'order' => 'ASC',
              'orderby' => 'menu_order ID'));

              foreach($attachments as $att_id => $attachment) {
                $full_img_url = wp_get_attachment_url($attachment->ID);
                echo wp_get_attachment_image($attachment->ID, 'full');
               
              }

【问题讨论】:

  • post_parent 是问题所在,当您在媒体库中上传图片时,post_parent 为空。当您从任何页面或帖子上传图片时,post_parent 将被设置为当前页面/帖子 ID。
  • 有什么办法可以解决吗? @维杰哈达哈

标签: wordpress image post wordpress-theming


【解决方案1】:

使用 get_posts 函数而不是 get_children。

这是一个示例,说明如何检索所有附加到帖子的图像,无论它们是使用帖子的“添加媒体”按钮添加的还是通过将它们直接上传到媒体库来添加的:

$args = array(
    'post_type' => 'attachment',
    'post_parent' => $post->ID,
    'post_mime_type' => 'image',
    'order' => 'ASC',
    'orderby' => 'menu_order ID',
);
$attachments = get_posts( $args );

foreach ( $attachments as $attachment ) {
    $full_img_url = wp_get_attachment_url( $attachment->ID );
    echo wp_get_attachment_image( $attachment->ID, 'full' );
}

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    相关资源
    最近更新 更多