【问题标题】:Add value to WP Attachment Meta Data为 WP 附件元数据增加价值
【发布时间】:2015-03-01 12:16:50
【问题描述】:

我想让 Wordpress 在上传媒体时计算纵横比和方向,而不是在模板中执行此操作。然后我可以调用 images 并询问 image.orientation,它会给我 'portrait' 或 'landscape' 作为值。

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

这是可能的还是我必须在前端这样做?

【问题讨论】:

    标签: wordpress upload orientation attachment aspect-ratio


    【解决方案1】:

    你可以为它写一些代码。使用http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata 获取宽度和高度,然后如果 $width/$height > 1 => 横向,否则为纵向。使用: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' );
    

    【讨论】:

    • 您好胡安,感谢您的回复。我无法让它工作。我重新上传了一些图像,但没有效果。有什么遗漏吗? // add orientation to attachments function attachment_orientation_meta(){ $attachmentInfo = wp_get_attachment_metadata( $id ); $attachmentOrientation = ( $attachmentInfo['height'] > $attachmentInfo['width'] ) ? 'portrait' : 'landscape'; $attachmentOrientationMeta = wp_update_attachment_metadata( $post_id, $attachmentOrientation ); return $attachmentOrientationMeta; } add_action( 'add_attachment', 'attachment_orientation_meta' );
    • 检查更新的答案。基本上,“add_attachment”操作将附件 ID 作为参数。然后你必须在你的函数中使用它。最后,update_attachment_metadata 需要一个数组作为第二个参数。我已经使用了上面的 update_post_meta,它“更容易”。
    • 感谢您的关注。从昨天开始,我一直在努力让它工作,但不幸的是我无法让它工作:(
    • 所以我测试了它,你是对的,钩子在检测到上传时工作,但读取元数据“为时过早”。我搜索了一下,但找不到后来的钩子,所以它可能不存在。在这种情况下,我的方法是:当您检测到新上传时,触发 cron 作业 (smashingmagazine.com/2013/10/16/…) 以在 1 分钟后执行,然后对该 cron 作业进行编码以获取元数据、更新附件元数据等。
    • 感谢您的方法。我会将此标记为解决方案。
    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 2018-10-18
    • 2017-09-16
    • 1970-01-01
    • 2022-08-03
    • 2016-05-07
    • 2015-08-11
    • 1970-01-01
    相关资源
    最近更新 更多