根据缩略图后方向向img容器添加类

问题描述 投票:0回答:1

我的函数中有一个脚本,它根据特色图像是横向还是纵向向其添加一个类。它的工作原理是根据给定帖子缩略图的宽度测量高度,并将类从

attachment-
附加到
horizontal-image attatchment-
中。

if ( ! function_exists( 'mytheme_vertical_check' ) ) :
    function mytheme_vertical_check( $html, $post_id, $post_thumbnail_id, $size, $attr ) {

        $image_data = wp_get_attachment_image_src( $post_thumbnail_id , 'large' );

        //Get the image width and height from the data provided by wp_get_attachment_image_src()
        $width  = $image_data[1];
        $height = $image_data[2];

        if ( $width > $height ) {
            $html = str_replace( 'attachment-', 'horizontal-image attachment-', $html );
        }
        return $html;
    }
endif;

add_filter( 'post_thumbnail_html', 'mytheme_vertical_check', 10, 5 );

但是,我需要将其添加到容器的类中,而不是将

horizontal-image
添加到实际的 IMG 类中。该容器是一个具有
masonry-thumbnail
类的 div。所以我希望适当的容器将
masonry-thumbnail horizontal
作为它们的类。

注意:这个函数的原作者建议我使用 jQuery 修复,在尝试了几个不同的代码字符串后,我意识到它不能很好地与无限滚动配合使用,因此最好使用来自在 WordPress 本身内部通过函数的方式,就像原始代码(运行完美)在页面最初呈现时附加类一样,而不是通过 jQuery 进行页面后加载。此外,我想尽可能少地使用 JavaScript。

php wordpress image class orientation
1个回答
4
投票

你可以尝试这样的事情。如果图像是横向的,则修改您的函数以仅返回“水平”类:

function mytheme_vertical_check() {

    $thumb_id   = get_post_thumbnail_id();
    $image_data = wp_get_attachment_image_src( $thumb_id , 'tp-thumbnail' );

    $width  = $image_data[1];
    $height = $image_data[2];

    if ( $width > $height ) {
        return 'horizontal';
    }
}

并在循环内调用它来将“水平”类添加到您选择的 div 中:

<?php if ( has_post_thumbnail() ) : ?>
    <?php printf( '<div class="masonry-thumbnail %s">', mytheme_vertical_check() );?>
        <?php the_post_thumbnail( 'large' ); ?>
    </div>
<?php endif; ?>
© www.soinside.com 2019 - 2024. All rights reserved.