You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress前端获取媒体库图片的自定义字段值

WordPress媒体库自定义字段前端获取方案

问题背景

我已在主题的functions.php中实现了两套可正常运行的后端媒体库自定义字段方案,每套方案均包含2个钩子:1个用于在媒体库编辑页展示新增的自定义字段,另1个用于字段值的保存与更新,两套方案的实现代码如下:

方法1

function media_hacks_attachment_field_to_edit( $form_fields, $post ){
    $media_author = get_post_meta( $post->ID, 'media_author', true );
    
    $form_fields['media_author'] = array(
        'value' => $media_author ? $media_author : '',
        'label' => __( 'Author' )
    ); 
    return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'media_hacks_attachment_field_to_edit', null, 2 );

// 保存字段值(方法1)
function media_hacks_edit_attachment( $attachment_id ){
    if ( isset( $_REQUEST['attachments'][$attachment_id]['media_author'] ) ) {
        $media_author = $_REQUEST['attachments'][$attachment_id]['media_author'];
        update_post_meta( $attachment_id, 'media_author', $media_author );
    }
}
add_action( 'edit_attachment', 'media_hacks_edit_attachment' );

方法2

function my_image_attachment_fields_to_edit($form_fields, $post) {
    // 向附件表单添加自定义字段
    $form_fields["custom1"] = array(
        "label" => __("Custom Text Field"),
        "input" => "text",
        "value" => get_post_meta($post->ID, "_custom1", true)
    );
     
    return $form_fields;
}
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);

// 保存字段值(方法2)
function my_image_attachment_fields_to_save($post, $attachment) {
    if( isset($attachment['custom1']) ){
        update_post_meta($post['ID'], '_custom1', $attachment['custom1']);
    }
    return $post;
}
add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null, 2);

后端媒体库运行效果(展示自定义文本字段与作者字段):
后台效果截图
以上后台仪表盘部分功能运行正常。

问题描述

需要在前端检索并展示这两个媒体自定义字段的值,在自定义PHP页面模板中做了如下尝试但未成功:

<tr id='MySpecialRow'>
    <td colspan='2' style='background:#000;color:#fff;'>
      <?php
        $args = array('cat' => 8);
        $query = new WP_Query($args);
        if ($query->have_posts()) {
          while ($query->have_posts()) {
            $query->the_post();
            $untitled_meta = rwmb_meta('image_advanced_8hswqfsoqai', '', get_the_ID());
            foreach ($untitled_meta as $image) {
              $media_author = get_post_meta( get_the_ID(), 'media_author', true );
              echo get_the_ID();// 可以正常输出文章ID
              echo $media_author;// 始终无输出
            }
          }
        }
      ?>
    </td>
</tr>

补充说明:

  • 代码中get_the_ID()可以正确打印当前文章ID,但$media_author变量始终无值输出;
  • 执行WordPress文章查询循环的原因是包含自定义字段的图片画廊存在于文章内容中,当前处于页面模板下无法直接获取对应ID。

问题原因

传入的ID错误。
媒体自定义字段是存储在附件(attachment)本身的post meta中,不是存储在附件所属文章的post meta里。原代码调用get_post_meta( get_the_ID(), 'media_author', true )时,传入的是当前循环的文章ID,不是遍历到的图片附件的ID,自然读不到对应值。

修复方案

rwmb_meta返回的图片数组$image本身就包含附件ID,直接用这个ID读取自定义字段即可,修正后的代码如下:

<tr id='MySpecialRow'>
    <td colspan='2' style='background:#000;color:#fff;'>
      <?php
        $args = array('cat' => 8);
        $query = new WP_Query($args);
        if ($query->have_posts()) {
          while ($query->have_posts()) {
            $query->the_post();
            // 获取文章关联的图片画廊数组
            $untitled_meta = rwmb_meta('image_advanced_8hswqfsoqai', '', get_the_ID());
            foreach ($untitled_meta as $image) {
              // 核心修改:用图片附件的ID读取meta,而非文章ID
              $media_author = get_post_meta( $image['ID'], 'media_author', true );
              $custom1_val = get_post_meta( $image['ID'], '_custom1', true );
              
              echo '文章ID:' . get_the_ID() . '<br>';
              echo '图片附件ID:' . $image['ID'] . '<br>';
              echo '图片作者:' . esc_html($media_author) . '<br>';
              echo '自定义文本字段值:' . esc_html($custom1_val) . '<br>';
            }
          }
          wp_reset_postdata(); // 循环结束重置全局post数据,避免影响后续查询
        }
      ?>
    </td>
</tr>

注意事项

  • 输出自定义字段值时需要用esc_html()做转义,避免XSS安全风险
  • 自定义WP_Query循环结束后必须调用wp_reset_postdata(),否则会打乱全局文章上下文
  • 两个自定义字段的meta_key不要写错:作者字段key为media_author,自定义文本字段key为_custom1(注意开头的下划线)

内容的提问来源于stack exchange,提问作者compliance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 04:15:15