【问题标题】:Wordpress: auto select category based on image aspect ratioWordpress:根据图像纵横比自动选择类别
【发布时间】:2016-06-14 19:33:23
【问题描述】:

我希望创建一个系统,当我创建帖子并上传并设置特色图片时,wordpress 会根据特色图片的纵横比选择创建的三个类别之一(风景、肖像或方形)

我一直在寻找如何实现这一目标的几个小时,而在我的一生中,我找不到任何东西。此外,我在网络开发方面是一个相当大的菜鸟,所以如果有人可以提供帮助;请提供代码、简化的解决方案或详细信息。

谢谢!

没有插件!

【问题讨论】:

  • 欢迎来到 SO,请在提问时更具体一点:您尝试过什么,您期望什么等。请参阅how to ask
  • 例如:如果我上传 16:9 的图像,它会自动选择类别“风景”如果图像是 1:1,那么如果图像是 9:16,它会自动选择“正方形”然后它会自动选择“肖像”.... 根据特色图片的纵横比让 wordpress 自动选择帖子的类别:“风景”、“肖像”或“方形”。

标签: php html wordpress image


【解决方案1】:

Wordpress 使用钩子概念:在某些事件中,它会调用附加到该事件的所有函数。例如,当您保存帖子时,wordpress 会执行do_action('save_post', $post_id),因此您可以处理最近保存的内容。我在这里提供了一个未经测试的代码,但它至少可以作为你找到方法的开始。

function check_thumbnail_size($post_id) {
    if (has_post_thumbnail($post_id)) {
        $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'full');

        if (is_array($thumbnail)) {
            $width = $thumbnail[1];
            $height = $thumbnail[2];
            $ratio = $width/$height;

            if ($ratio == 1) {
                $term_slug_or_id = 'ratio'; // change this to your term slug or ID
            } elseif ($ratio > 1) {
                $term_slug_or_id = 'landscape';
            } else {
                $term_slug_or_id = 'portrait';              
            }
            wp_set_object_terms( $post_id, $term_slug_or_id, 'YOUR_TAXONOMY_NAME_HERE', TRUE); 
        }
    }
}
add_action('save_post', 'check_thumbnail_size');

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 2023-04-03
    • 2018-10-25
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多