在wordpress中检索具有特定大小的自定义字段图像


retrieve a custom field image with a specific size in wordpress

我正在使用Custom MetaBoxes 2创建一个图像上传器字段。

这是代谢盒的代码:

$meta_boxes['home_page_slider'] = array(
        'id'           => 'home_page_slider',
        'title'        => __( 'Home Page Slider', 'cmb2' ),
        'object_types' => array( 'page', ), // Post type
        'context'      => 'normal',
        'priority'     => 'high',
        'show_names'   => true, // Show field names on the left
        'show_on'      => array( 'id' => array( 5, ) ), // Specific post IDs to display this metabox
        'fields'       => array(
            array(
                'name'         => __( 'Slider Images', 'cmb2' ),
                'desc'         => __( 'Upload or add multiple images/attachments.', 'cmb2' ),
                'id'           => $prefix . 'slider-images',
                'type'         => 'file_list',
                'preview_size' => array( 100, 100 ), // Default: array( 50, 50 )
            ),
        )
    );

如何检索上传到该字段但具有特定大小(例如"Full")的图像,并在以下HTML标记的前端显示这些图像?

<ul class="slides">
  <li>
    <img src="images/awn1.jpg" />
  </li>
  <li>
    <img src="images/awn2.jpg" />
  </li>
  <li>
    <img src="images/awn3.jpg" />
  </li>
</ul>

此代码将完成以下操作:

<ul class="slides">
<?php
    $images = get_post_meta( 5, 'slider-images', true);
            if ( $images ) {
              foreach ( $images as $attachment_id => $img_full_url ) {
               $full = wp_get_attachment_link($attachment_id, 'full');
                echo "<li>";
                echo $full;
                echo "</li>";
              }
            }
?>
</ul>
  • 使用相同的可重复组前缀更改前缀
  • "5"是你帖子的id,或者像"get_the_id();"自动获取id
  • "full"是图像大小的名称,也许在你身边它是不同的,因为你可以使用默认的wp缩略图大小,即"thumbia"或其他大小,如"full,medium,large"

请尽情享受,如果你觉得我的回答有帮助,请给我打分。

谢谢。最好的EF。

查看文档https://github.com/WebDevStudios/Custom-Metaboxes-and-Fields-for-WordPress/wiki/Field-Types#file,有一个例子正好说明了你想要什么。

array(
    'name' => 'Test File',
    'desc' => 'Upload an image or enter an URL.',
    'id' => $prefix . 'test_image',
    'type' => 'file',
    'allow' => array( 'url', 'attachment' ) // limit to just attachments with array( 'attachment' )
),
$image = wp_get_attachment_image( get_post_meta( get_the_ID(), 'test_image_id', 1 ), 'medium' );

其中get_the_ID是您将图像上传到的帖子的ID