下面是我们用来通过WordPress的主题定制器将图像文件设置为网站徽标选项的代码:
/* Logo > Image
-------------------------------------------------- */
$wp_customize->add_setting( \'themeslug_logo\' );
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize, \'themeslug_logo\', array(
\'label\' => __( \'Logo\', \'themeslug\', \'themeslug\' ),
\'section\' => \'themeslug_header\',
\'settings\' => \'themeslug_logo\',
\'description\' => \'Upload a logo to replace the default site name in the header.\',
)
)
);
因此,我们展示的徽标如下:
<img src=\'<?php echo esc_url( get_theme_mod( \'themeslug_logo\' ) ); ?>\' alt=\'<?php echo esc_attr( get_bloginfo( \'name\', \'display\' ) ); ?> Logo\' class="img-responsive">
然而,在这样做时,我们意识到我们没有设置图像的高度/宽度属性。
因此,我们要完成的是从上传的媒体文件中提取图像高度/宽度,将其存储为变量,然后执行它们,如:
<?php
$logo = get_theme_mod( \'themeslug_logo\' );
$logoatts = wp_get_attachment_metadata($logo); // obviously doesn\'t work
$logoheight = ; // don\'t know how to get this
$logowidth = ; // don\'t know how to get this
?>
<img
src=\'<?php echo esc_url( get_theme_mod( \'themeslug_logo\' ) ); ?>\'
alt=\'<?php echo esc_attr( get_bloginfo( \'name\', \'display\' ) ); ?> Logo\'
class="img-responsive"
height="<?php echo($logoheight);?>"
width="<?php echo($logowidth);?>"
>
从本质上讲,我们遇到的问题是:我们希望从文件中获取根据WP\\u Customize\\u image\\u Control()设置的图像宽度,而不仅仅是URL。
提前感谢
SO网友:Vinicius Garcia
这个问题的现代答案:
我们有WP_Customize_Media_Control
WP中的控制自4.2 这将为您提供附件id。
此答案发布在I上similar question.您可以查看的文档WP_Customize_Media_Control
here.
使用示例:
$wp_customize->add_setting( \'my_menu_image\' );
$wp_customize->add_control( new \\WP_Customize_Media_Control(
$wp_customize,
\'storms_menu_image_ctrl\',
array(
\'priority\' => 10,
\'mime_type\' => \'image\',
\'settings\' => \'my_menu_image\',
\'label\' => __( \'Image on menu bar\', \'my\' ),
\'section\' => \'title_tagline\',
)
) );
检索信息时,可以执行以下操作:
$image_id = get_theme_mod( "my_menu_image" );
if ( ! empty( $image_id ) ) {
$url = esc_url_raw( wp_get_attachment_url( $image_id ) );
$image_data = wp_get_attachment_metadata( $image_id );
$width = $image_data[\'width\'];
$height = $image_data[\'height\'];
}
SO网友:user1503606
以上答案绝对是通过自定义获取图像大小的最佳方法,这里有一些额外的信息。
// Add your customizer block
$wp_customize->add_setting(
\'logo\'
);
$wp_customize->add_control(
new WP_Customize_Media_Control(
$wp_customize,
\'logo\',
array(
\'label\' => __(\'Logo\', \'theme\'),
\'section\' => \'styles\',
\'settings\' => \'logo\',
)
)
);
// Add your image size to your function.php file
add_image_size(\'logo_image_size\', 100, 9999, false);
// Output your media anywhere in your theme
$logo = get_theme_mod( "logo" );
if ( !empty($logo) ) {
echo wp_get_attachment_image( $logo, \'logo_image_size\' ) ;
}