[英]Making custom field appear in captions for image attachments (Wordpress)
我是在Wordpress网站上为客户工作的设计师(而非开发人员)。 通过使用ACF插件,我在媒体文件上为照片积分设置了自定义字段。 这在精选图片上效果很好,我可以在single.php中这样称呼它:
$post_thumbnail = get_post(get_post_thumbnail_id());
$credit = get_field('media_credit', $post_thumbnail);
if($credit):
echo '<div class="media-credit"><p>Photo: '.$credit.'</p></div>';
endif;
因此,我知道自定义字段可以工作,并且可以输出正确的数据。 但是,我无法将其用于帖子中的图像附件。 我所拥有的是:
add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode', 10, 3 );
function my_img_caption_shortcode( $empty, $attr, $content ){
$attr = shortcode_atts( array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
), $attr );
if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
return '';
}
if ( $attr['id'] ) {
$attr['id'] = 'id="' . esc_attr( $attr['id'] ) . '" ';
}
//OUTPUT CREDIT
$photographer = get_field( 'media_credit', $attachment_id );
if ($photographer):$media_byline = '<br/><span class="media-credit">Photo: '.$photographer.'</span>';endif;
return '<div ' . $attr['id']
. 'class="wp-caption ' . esc_attr( $attr['align'] ) . '" '
. do_shortcode( $content )
. '<p class="wp-caption-text">' . $attr['caption'] . '' . $media_byline . '</p>'
. '</div>';
}
如果删除OUTPUT中的if语句,则在标题后的标题应显示«Photo:»,但它不会得到任何数据。 我想念什么?
(顺便说一句,我知道有一些插件可以输出图像学分,但是它们倾向于具有我必须要覆盖的样式和功能,导致我不愿将意大利面乱七八糟的东西移交给下一个在此站点工作的家伙。)
终于有了这个工作! :-D而不是使用$attachment_id
,我从$attr
获得了ID,然后从输出中删除了'attachment_'前缀。
我还为摄影师和摄影局分别设置了领域,但我想这是重点。
这是代码:
function my_img_caption_shortcode( $empty, $attr, $content ){
$attr = shortcode_atts( array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
), $attr );
if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
return '';
}
$credit_id = $attr['id'];
$credit_id = str_replace( 'attachment_', '', $credit_id );
$photographer = get_field( 'media_credit', $credit_id );
$bureau_credit = get_field( 'media_bureau', $credit_id );
if ( $photographer && $bureau_credit ): $dash = ' / ';
endif;
if ( $photographer || $bureau_credit ): $media_byline = '<br/><span class="media-credit">PHOTO: '
. $photographer . ''
. $dash . '<span class="bureau-credit">'
. $bureau_credit
. '</span></span>';
endif;
return '<div id="attachment_' . $credit_id . '"'
. 'class="wp-caption ' . esc_attr( $attr['align'] ) . '" '
. do_shortcode( $content )
. '<p class="wp-caption-text">' . $attr['caption'] . '' . $media_byline . '</p>'
. '</div>';
}
add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode', 10, 3 );
这个解决方案是我从AFC Media Credit插件中提炼出来的 ,因此可以归功于开发人员。
我希望这对于想要实现类似目标的任何人都是有用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.