为 WP 附件元数据增加价值

Add value to WP Attachment Meta Data

我想让 Wordpress 在上传媒体时计算宽高比和方向,而不是在模板中执行此操作。然后我可以调用图像并请求 image.orientation 这将给我 'portrait' 或 'landscape' 作为值。

例如,上传图片后的样子:

这可能吗,还是我必须在前端执行此操作?

你可以为它写一些代码。使用 http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata to get the width and the height, and then if $width/$height > 1 => landscape, otherwise its portrait. Store this value in the attachment using: http://codex.wordpress.org/Function_Reference/wp_update_attachment_metadata.

您可以为此使用一个操作,例如:

add_action('add_attachment', 'process_images');

根据您的代码尝试添加解决方案(我还没有测试过):

function attachment_orientation_meta($id){
    $attachmentInfo = wp_get_attachment_metadata($id);
    $attachmentOrientation = ( $attachmentInfo['height'] > $attachmentInfo['width'] ) ? 'portrait' : 'landscape';
    update_post_meta($id, 'orientation', $attachmentOrientation);
}
add_action( 'add_attachment', 'attachment_orientation_meta' );