WordPress:根据图像纵横比自动选择类别


Wordpress: auto select category based on image aspect ratio

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

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

谢谢!

没有插件!

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');

希望对您有所帮助!