我正在尝试将筛选器添加到the_content
将在帖子中查找所有图像并附加自定义附件元数据credit
对它。
以下是我的功能:
Adds the Credit field to attachment details page: (这很有效)
function attachment_field_credit( $field, $post ) {
$field[ \'credit\' ] = array(
\'label\' => \'Credit\',
\'input\' => \'text\',
\'value\' => get_post_meta( $post->ID, \'credit\', true ),
);
return $field;
}
Saves the Credit field: (这很有效)function attachment_field_credit_save( $post, $attachment ) {
if( isset( $attachment[ \'credit\' ] ) )
update_post_meta( $post[ \'ID\' ], \'credit\', $attachment[ \'credit\' ] );
return $post;
}
Search the content for all available images: (这很有效)function find_images( $content ) {
return preg_replace_callback( \'/(<\\s*img[^>]+)(src\\s*=\\s*"[^"]+")([^>]+>)/i\', array( $this, \'attach_image_credit\' ), $content );
}
Appends credit metadata to each image: (这不起作用)function attach_image_credit( $images ) {
global $post;
$credit = get_post_meta( $post->ID, \'credit\', true );
$replacement = $images[0] . $credit;
return $replacement;
}
如果我更换
$credit
具有的值
<span>Hello World!</span>
文本将按预期显示在页面上。我的方式一定有问题
get_the_meta
的值
credit
.
<小时>
UPDATE
如果我手动更换:
get_post_meta( $post->ID, \'credit\', true );
使用:
get_post_meta( 446, \'credit\', true );
它起作用了!所以我需要做的就是找出一种获取附件ID的方法。
最合适的回答,由SO网友:TheDeadMedic 整理而成
因为信用数据保存在附件的post meta中,而不是主post中:
$credit = get_post_meta( $post->ID /* Wrong ID! */, \'credit\', true );
相反,您需要捕获插入图像的ID:
function attach_image_credit( $images ) {
$return = $images[0];
// Get the image ID from the unique class added by insert to editor: "wp-image-ID"
if ( preg_match( \'/wp-image-([0-9]+)/\', $return, $match ) ) {
if ( $credit = get_post_meta( $match[1] /* Captured image ID */, \'credit\', true ) )
$return .= $credit;
}
return $return;
}