pixelshelsinki / images
WordPress的响应式图片组件
v1.0.3
2024-05-15 14:08 UTC
Requires (Dev)
- php-stubs/wordpress-stubs: ^6.0
- phpunit/phpunit: ^9
- squizlabs/php_codesniffer: ^3.5
- vimeo/psalm: ^5.0
README
WordPress的响应式图片组件。处理视网膜尺寸和不同形状的图片。
- 允许图片有普通和视网膜尺寸
- 允许图片在不同长宽比下有不同的移动端图片
- 自动处理懒加载
- 使用图片标签,为背景图片设置自定义背景样式。
安装
composer require pixelshelsinki/images
使用方法
Pixels Images 包含用于处理图片的独立类和一个用于轻松使用的静态工厂。在使用新的图片处理器之前,您只需使用工厂类注册图片尺寸。
注册图片尺寸。
在您的主题/插件中声明您的图片尺寸。'init'动作钩子是一个好位置。
<?php use Pixels\Components\Images\Factory as ImageFactory; /** * Image sizes array * Pattern: * * NAME, WIDTH, HEIGHT, CROP, RETINA TRUE/FALSE * * @var array */ $sizes = array( 'page-hero' => array( 1100, 500, true, true ), 'page-hero-mobile' => array( 375, 500, true, true ), ); // Register sizes to image factory. ImageFactory::add_image_sizes( $sizes ); /** * You can also optionally register css-style breakpoint for mobile / desktop. * Default is 576px. */ ImageFactory::add_breakpoint( '600px' );
使用响应式图片。
PHP中使用方法
<?php use Pixels\Components\Images\Factory as ImageFactory; $image_html = ImageFactory::responsive_image( $image_id, 'my_mobile_size', 'my_desktop_size', 'my alt text' ); echo $image_html;
使用响应式背景。
PHP中使用方法。注意,具有给定CSS选择器的元素必须存在于DOM中。可以是任何有效的CSS选择器,如类或ID。
<?php use Pixels\Components\Images\Factory as ImageFactory; $image_html = ImageFactory::responsive_background( $image_id, 'my_mobile_size', 'my_desktop_size', '#my_html_element' ); echo $image_html;
与Twig / Timber一起使用。
最简单的方法是将工厂函数注册为Twig辅助函数。
<?php add_filter( 'get_twig', array( 'add_image_functions' ) ); function add_image_functions( $twig ) { // Responsive mage helper functions. $twig->addFunction( new \Timber\Twig_Function( 'responsive_image', '\\Pixels\\Components\\Images\\Factory::responsive_image' ) ); $twig->addFunction( new \Timber\Twig_Function( 'responsive_background', '\\Pixels\\Components\\Images\\Factory::responsive_background' ) ); return $twig; }