【问题标题】:Alter <img> with custom media field data使用自定义媒体字段数据更改 <img>
【发布时间】:2016-03-02 17:17:20
【问题描述】:

我已使用以下代码将一些自定义字段添加到我的媒体附件详细信息...

function aj_attachment_field_audio_url( $form_fields, $post ) {

$form_fields['aj-audio-url'] = array(
    'label' => 'Audio File URL',
    'input' => 'text',
    'value' => get_post_meta( $post->ID, 'aj-audio_url', true ),
    'helps' => 'Add Audio URL',
);

return $form_fields;
}

add_filter( 'attachment_fields_to_edit', 'aj_attachment_field_audio_url', 10, 2 );

function aj_attachment_field_audio_url_save( $post, $attachment ) {

if( isset( $attachment['aj-audio-url'] ) )
    update_post_meta( $post['ID'], 'aj_audio_url', esc_url( $attachment['aj-audio-url'] ) );
return $post;
}

add_filter( 'attachment_fields_to_save', 'aj_attachment_field_audio_url_save', 10, 2 );
?>

我现在不知道如何更改我的 img 标签以包含带有 data-audio_url="" 的新信息。

基本上,只要有一个带有该字段的图像(添加到内容所见即所得)我想将其添加到 img 标签。

如有任何帮助,将不胜感激。

谢谢你

【问题讨论】:

    标签: php wordpress filter action hook


    【解决方案1】:

    使用 get_image_tag() 可能会到达您想要的位置。以下内容未经测试,但应该可以工作。

    function get_image_tag( $id, $alt, $title, $align, $size ) {
    
        //Getting the meta data
        $aj_audio_url = get_post_meta( $id, 'aj_audio_url', true );
    
        //If not empty add the audio_url
        if ( ! empty( $aj_audio_url ) ) {
           $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . ' data-audio_url="' . $aj_audio_url .  '"/>';
    
           return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
        }
    }
    

    在此处获取更多信息和示例: https://developer.wordpress.org/reference/functions/get_post_meta/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 2019-11-03
      • 2014-01-10
      • 1970-01-01
      相关资源
      最近更新 更多